Friday, December 28, 2012

Java - Get content type of a particular file



In many occasion you may require to check content type of a particular file. For example if a file is uploaded, it's not enough to check only file extension. For additional security you should also check the actual content type of a file so latter while processing the file no exception occurs. File could be Image, Excel, Text etc.

Let's see how this can be achieved in Java.

URL - This class represents a Uniform Resource Locator. It point to a particular resource, resource can be either a file , directory or an object. Here it refers to a file.

URLConnection - This is the super class of all classes that represent a communication link between an application and a URL.

openConnection() - This is the method of URL class which represents a connection to the remote object referred to by the URL.

getContentType() - This method of URLConnection class returns the content type of the file.

Views in SQL Server



SQL Server helps you to store data so that it can be retrieved easily. SQL Server is form of Relational Database Management System (RDBMS) i.e. data is stored as combination of columns and rows (tables) that are related to each other in a database. It provides various services such as integrating different database, reporting services, security of data. One of the important features is security that provides access to user based on their roles. One form that security can be enabled is by using views.

There are three uses of views in SQL Server:


  • When we want to restrict access of columns to some users 
  • It helps simplify query execution when the users need to access data from multiple tables frequently that can be performed by using joins
  • When there is a large data in tables,  multiple views can be created, each view having manageable data and the database can be managed by multiple users who will handle that amount of data which makes the process of handling database efficient


A view is basically a virtual table that provides access to subset of columns from one or more tables. It is a query stored as an object in database that does not have its own data. It derives data from one or more tables called as underlying table. There is view known as syscomments view which is system defined view that stores entries for each view and other objects. This view contains a text column that stores the original SQL definition statement.

There are some restrictions at the time of modifying data through views:

  • You cannot modify table if the modification affects more than one table at a time
  • You cannot change a column that is result of a calculation such as a computed column or an aggregate function


Learning JavaScript



JavaScript is basically a scripting language that makes browsers more interactive. Browsers have limited functionality that is used to understand only text, images, tables or frames. It is used to respond to user input and take action based on the input. It allows interactivity through improved appearance, site navigation, performing calculations, validation of inputs. It is embedded on Html pages and does not need separate installation. It is an interpreted and not compiled language which means that it is executed directly on client side. It is generally misinterpreted that JavaScript is similar to Java but it is not true. In fact, it has nothing to do with Java.

Let us learn start with basic JavaScript code in any text editor:

<body>
<script language="JavaScript">
document.write('This is first  JavaScript Page');  /* it simply outputs the text inside parentheses*/
</script>
</body>

JavaScript is very good at processing user input in the web browser. HTML <form> elements receive input.

Comments in JavaScript is similar to any programming language such as C++, Java, C# i.e. for single line "//" and for multiline "/* your code here */".

Data type declaration in JavaScript is very unique in the sense that it uses only "var" as the declaration for the irrespective of kind of data.

E.g.

var x=2; /*Here x acts as integer. */

var x="Mitesh"; /*Here x acts as string */.

So, it dynamically takes data based on the input. But, you must note one point that unlike other programming language, the variable must be declared at declaration time unless data type is an array, then you must give the size of that array. JavaScript code is embedded inside the Html code. There is also escape character "\" used to tell the JavaScript that the code just after this tag should not be parsed E.g. \n  //new line.

Technology to help track spread of cancer cells

In a first of its kind integration between technology and medical fields, scientists are using the equations Google employs to predict the Web page users visit to track the spread of cancer cells throughout the body. It is based on an assumption that each of the sites where a spreading or metastatic tumour could show up is analogous to the web pages. Google ranks web pages by the likelihood that an individual would end up visiting each one randomly. These findings are based on the trends of millions of users by analysis from the web using “steady state distribution”. Steady state distribution is similar to the metastatic tumour distribution that shows up in the autopsy datasets. The dataset contains information about autopsy patients from the 1920’s to 1940’s, who died before chemotherapy was available. By focusing on these patients, the researchers tracked the natural progression of cancer without different treatments interfering with the data. These inferences are based on details from Paul Newton, a mathematician at the University of Southern California, who has been working at the Scripps Research Institute. Out of the fifty metastasis sites described in the autopsy reports, scientists found that most of them contained cancer cells that seem to have spread from the lungs. Just like with a person browsing the web, cells that break from the original lung tumour and entered the bloodstream have a certain probability of progressing to the different locations. Learning from the Google’s example with search results, researchers estimated that average time it takes the cancer to spread to the different parts of the body was less. The lymph nodes are the quickest to be affected by metastasizing lung cancer cells, and then adrenal gland and lastly liver.

Thursday, December 27, 2012

MSpy the new word in mobile tracking software


mSpy: the new word in a cell phone tracking software technology

Not knowing at all is mostly much more harmful than being lied to. The situation really
doesn’t matter. You could have an employee misusing the property of your company or is not
performing the job properly. You could be a concerned parent whose child is getting involved in
wrong activities which may bring some serious troubles for him/her. You could be the one with a
husband, wife, boyfriend or girlfriend that is cheating on you. In any case, it is important for you
to keep an eye on every detail in order to find out whether the person is honest or is constantly
lying to you. That is the time when MSpy can play its part.

How can MSpy help you?

As the name indicates- MSpy tracks the mobile phones. Many big companies keep a constant
check on the cell phone and internet activities of their employees in order to make sure that they
are not providing the confidential data or trade secrets to someone else. MSpy does nearly the
same thing for you. Once you install MSpy, you would be able to get access to all calls received
and made, text messages received and sent, internet usage and pictures taken etc. MSpy can
provide you access to almost every activity performed on the mobile phone.

Tuesday, December 25, 2012

JDBC example using MS Access

Lets see a simple JDBC example using MS Access.

We are using below mentioned particulars
  • MS Access 2007
  • Java 1.6
Step 1. Create Database using MS Access

Create a New blank database, Name the file EmployeeMgmt.mdb and save it in your desire location. Please see the screen shot below.


Create the columns empId and empName in table employee as shown below. Also add few records which we will be fetching through Java code i.e JDBC.



Monday, December 24, 2012

JDBC Example – Batch Update using PreparedStatement


Using Batch Update feature of PreparedStatement you can Insert, Update or Delete multiple records with single database hit. For example if you want to insert multiple records into database using Batch Update you will just need to conect to database once. You can loop through records and add it to bach and once done you can execute the bach i.e insert all records in a single shot.


Below is a code snippet which shows how to insert few records in batch process, via JDBC PreparedStatement

PreparedStatement ps=con.prepareStatement("INSERT INTO BS_Books (cat_id,book_title,book_details,book_price,book_author) values (?,?,?,?,?)");

ps.setInt(1, 1);
ps.setString(2, "Book1");
ps.setString(3, "Details of book1");
ps.setDouble(4, 100.0);
ps.setString(5, "Author1");
ps.addBatch();//Adding record to the batch

ps.setInt(1, 1);
ps.setString(2, "Book2");
ps.setString(3, "Details of book2");
ps.setDouble(4, 150.0);
ps.setString(5, "Author2");
ps.addBatch();//Adding record to the batch

ps.executeBatch();//Executing the batch

Please see the complete self explanatory java code below


Hibernate reverse engineering demo using Eclipse

Reverse Engineering: The most powerful feature of Hibernate Tools is a database reverse engineering tool that can generate domain model classes and Hibernate mapping files, annotated EJB3 entity beans, HTML documentation or even an entire JBoss Seam application in seconds. With the help of Eclipse you can do reverse Engineering. Lets see step by step to reverse-engineer database tables to generate hibernate POJO classes and mapping XML files using hibernate-tools (eclipse).

About the example: I am using My Eclipse 8.6 and MySQL. We will generate POJO classes and mapping XML files etc and latter run a test program. Please see the self explanatory screen shots below.

1. Create a New Java project
File -> New -> Java Project


Hibernate Examples - Native SQL Queries


You can also express queries in the native SQL dialect of your database. This is useful if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. It also provides a clean migration path from a direct SQL/JDBC based application to Hibernate.

Hibernate3 allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

To know more, click here.

For example - we can have methods in DAO for executing Native SQL as shown below.

public List executeNativeQuery(String query) {
return getSession().createSQLQuery(query).list();
}

public List executeQuery(String query) {
return getSession().createQuery(query).list();
}

You can pass native SQL query as shown below -

List allObjects = empDao.executeNativeQuery("Select emp_id, emp_name  from EMPLOYEE");

Iterator it = allObjects.iterator();
while(it.hasNext())
{
Object row[] = (Object[])it.next();
for(Object eachRow : row) {
System.out.println(eachRow.toString());
}
}

Below are the known errors and exception -

1. Exception in thread "main" org.hibernate.MappingException: No Dialect mapping for JDBC type: -1
at org.hibernate.dialect.TypeNames.get(TypeNames.java:79)
at org.hibernate.dialect.TypeNames.get(TypeNames.java:104)
at org.hibernate.dialect.Dialect.getHibernateTypeName(Dialect.java:393)
at org.hibernate.loader.custom.CustomLoader$Metadata.getHibernateType(CustomLoader.java:582)
at org.hibernate.loader.custom.CustomLoader$ScalarResultColumnProcessor.performDiscovery(CustomLoader.java:508)
at org.hibernate.loader.custom.CustomLoader.autoDiscoverTypes(CustomLoader.java:524)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1821)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
at org.hibernate.loader.Loader.list(Loader.java:2124)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)


Solution - Above exception occurs if you pass * to fetch all columns in SQL like - "Select * from EMPLOYEE". this should be avoided.


Monday, December 10, 2012

Lucene - Updating index for an existing file


Updating index files could mean below two possibilities -
  • Adding a new file to existing index
  • Updating an existing file

Adding a new file to an existing index

Adding a new file is very simple. Please see my previous article. click here.

Updating an existing file

When you do IndexWriter.add() for a document that is already in the index it won't overwrite the previous document instead it will add multiple copies of the same document in the index.

There is no direct update procedure in Lucene. To update an index incrementally you must first delete the documents that were updated, and then re-add them to the index. In this example we will see how to delete a file and then you can re-add the same file with the help of my previous article. click here.

How to delete a documents from the index?

IndexWriter allows you to delete by Term or by Query. The deletes are buffered and then periodically flushed to the index, and made visible once commit() or close() is called.

IndexReader can also delete documents, by Term or document number, but you must close any open IndexWriter before using IndexReader to make changes (and, vice/versa). IndexReader also buffers the deletions and does not write changes to the index until close() is called, but if you use that same IndexReader for searching, the buffered deletions will immediately take effect. Unlike IndexWriter's delete methods, IndexReader's methods return the number of documents that were deleted.

Generally it's best to use IndexWriter for deletions, unless 1) you must delete by document number, 2) you need your searches to immediately reflect the deletions or 3) you must know how many documents were deleted for a given deleteDocuments invocation.

If you must delete by document number but would otherwise like to use IndexWriter, one common approach is to make a primary key field, that holds a unique ID string for each document. Then you can delete a single document by creating the Term containing the ID, and passing that to IndexWriter's deleteDocuments(Term) method.

Once a document is deleted it will not appear in TermDocs nor TermPositions enumerations, nor any search results. Attempts to load the document will result in an exception. The presence of this document may still be reflected in the docFreq statistics, and thus alter search scores, though this will be corrected eventually as segments containing deletions are merged.

To know more, click here.

Friday, November 9, 2012

Some Smart Social Media Marketing Tips


In today world, social media is the finest and essential way to market your business successfully. It is not an easier task especially with the lack of proper knowledge and understanding about different social media marketing strategies. There is large number of social media networks such as twitter, Google plus, Facebook, my space and so on which act as the powerful medium to market business and this is the reason  many business are hiring digital media agency that are expert in marketing strategy to market your business on social media. For some extent you can also do social media marketing of your business, here are some smart tips for social media marketing:

Post content which your target audience like to read not the content which you like to read. Many beginners write content based on their taste without considering type of the audience they are writing. Blogging about being businessman is good if your audience are business owners.
Determine social media marketing return on investment by examining and comparing return on investment on other advertising methods. Instead of comparing each and every thing, it will be better to compare the amount of traffic different channels are driving to your site.
Offer mobile check-in deals to provide products and services

Tuesday, November 6, 2012

Simple Java program to Watermark an Image

A watermarking is a technique that allows an individual to add copyright notices or other verification messages to digital audio, video, or image signals and documents. It  may be visible, hidden, or a combination of both. Lets see how it can be achieved using a simple Java program. Below is the simple code however you can customize it according to your requirement.

Please see the self explanatory Java program below.


MySQL - JDBC example for BLOB storage

A blob (binary large object) is a collection of binary data stored as a single entity in a database. Blobs can be used to store images, audio or other multimedia files. There are four variation of blob datatype -
  • TINYBLOB - Maximum length of 255 (2^8 - 1) characters i.e 25 bytes
  • BLOB - Maximum length of 65535 (2^16 - 1) characters i.e 64 KB
  • MEDIUMBLOB - Maximum length of 16777215 (2^24 - 1) characters i.e 16 MB
  • LONGBLOB - Maximum length of 4294967295 (2^32 - 1) characters i.e 4GB

About the example: We will create a table in mySql and see how to insert/reterive an image using JDBC.

First lets create a table in MySQL. Please see the syntax below, we have used MEDIUMBLOB as it would be sufficient for medium size object stotage. You can use any other as per your requirement. We have just 3 columns pic_id as a auto increment primary key, pic_name will hold the picture name and pic_file a blob which will store actual picture.

CREATE TABLE blobtest (
pic_id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (pic_id),
pic_name VARCHAR(100) NOT NULL,
pic_file MEDIUMBLOB
);


Monday, November 5, 2012

How to iterate Java object in JavaScript using JSON?


You may require passing a java object to javascript and iterating through it. Java object could be literally anything whether it List, Map, List of Map, Map of List etc.
For example: ArrayList<String>, Hashtable<String,String>, ArrayList<Hashtable<String,String>>, Hashtable<String,ArrayList<String>> etc.

This can be easily achieved using JSON. To run below JSP you need to include json-simple-1.1.1.jar in classpath. Download the JAR file from http://code.google.com/p/json-simple/

About the example: In below example I have created a java object i.e. HashMap<String, ArrayList<String>>. Add some values to the object. Convert the object into JSON string using method JSONValue.toJSONString(). In JavaScript pass the JSON string to JSON.parse() and get the corresponding JavaScript object. Now you are ready to iterate it using below syntax. Please see the self explanatory example below.

Friday, November 2, 2012

Convert an object to json string and vice versa in Java and Javascript

Today we will see how to convert an object to json string and vice versa. An object could be JSONObject or any Java Object for example Map of list, List of map etc. Also please see my earlier post on Java Examples for JSON encoding, click here.

Note - To run below examples you need to include json-simple-1.1.1.jar in classpath. Download the JAR file from http://code.google.com/p/json-simple/

Example 1 : Convert JSONObject to JSON String and vice versa

Output :

{"Name":"Ramesh","Nickname":null,"Salary":15000.0,"isPermanent":true,"EmployeeId":121}
121
Ramesh
15000.0
true
null

Thursday, November 1, 2012

JSTL: How to access fmt:message from Javascript


You might have seen How to use fmt:message and ResourceBundle from JSP and Java in my earlier post, click here.

Now we will see how to use fmt:message from Javascript. Its very simple to use JSTL's fmt tag in JavaScript to localize alert messages.

I found two ways in which you can access values from a property file in javascript. Please see the sample codes below.

Method 1.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<script type="text/javascript">
<!--
var msg = {
prop1: "<fmt:message key="prop1" />",
prop2: "<fmt:message key="prop2" />"
};

function test() {  
 alert(msg.prop1);
alert(msg.prop2);
}

//-->
</script>

Method 2.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<script type="text/javascript">
<!--
<fmt:message key="prop1" var="prop1"/>    
var prop1 = "${prop1}";

function test() {  
 alert(prop1);
}

//-->
</script>

Friday, October 26, 2012

2012: A Year in Review of Cyber Crime


The worst fear of many computer users is waking up one day only to find out they have had their bank
account emptied to the last penny and their identity stolen. The worst part about it is that this is exactly
what happens to thousands of Americans each week and to even more people worldwide.

The unfortunate fact is that 2012 was another year in which millions of people were affected by cyber
crime in some way, be it that they were simply recipients of fraudulent emails, infected by a virus or had financial property stolen from them.

In fact, there have already been two major cyber crimes that have affected hundreds of thousands of
people this year alone.

1. The Reveton Virus: Your Computer as Ransom

It is one thing to have your personal data and financial information held at ransom, but it is a completely
new thing to have your computer locked until you pay up.

That's exactly what the Reveton virus does. It locks renders your computer unable to be used until you
pay the malicious people behind it a certain amount of money.

The Reveton virus installs itself on a user's computer when the user opens an email attachment. Once
the attachment is opened, a bogus screen pops up and says that the user's computer has been disabled.
The only way to reactivate it is to pay a “fine” by using a prepaid card service that hackers use to scam
people out of their money.

There's another reason that this malware weighs in at the most dangerous of 2012, it often leaves other
malicious software on the user's computer, which can then steal the user's confidential information
even after he or she has paid the ransom.


Top 5 Kindle Fire HD Accessories


It was Apple's day yesterday, but today it's a bit easier to see things in a more neutral light. With that $329 price point, the $199 Android tablets like the Nexus 7 and Kindle Fire HD aren't too threatened - Apple have gone into the market with a premium product at a premium pricepoint, and the $199 line will continue for now. Indeed, for a product that is $130 cheaper the Fire HD is surprisingly competitive, with a higher resolution display better suited for video and game content as well as a rich books ecosystem that rivals Apple's.

Today we'll be considering this tablet and some of the best accessories that are available for it on the market - if you're trying to choose between this and an iPad Mini, does that mean you have $130 to spend on Kindle Fire accessories? It's not a bad plan... let's see what we can get for that sum!


5. Slimline Rotating Leather Style Stand Case

We'll start off with a Slimline Leather Style Case. This Kindle Fire HD case is relatively inexpensive and available in multiple colours to allow you to really express yourself beyond the bland black colour of the Fire HD. The case also includes a rotating stand that allows you to stand your Kindle Fire HD in portrait or landscape modes easily, making it perfect for playing games, watching films or browsing the web. All with that leather look and feel, but without the environmental impact of real leather.




Businesses Utilize Twitter to Hear Consumers


One of the most important aspects of any business is to know when the consumer needs a change in the products or services that are offered. When consumers talk about a service or product offered, it is vital that the business listens. There is no better way for a business to listen than through the use of social media options on the market. In particular, most businesses are finding a ton of success with the use of Twitter to listen to their consumers.

Why Twitter?

The reason so many businesses find Twitter to be the better social media site to use is because the
tweets are short and to the point. There are no huge paragraphs to read through in order to find out
what people liked and did not like. It is simple and to the point. When a business has followers on
Twitter, whether these are those who found the company or followers that the company utilized the
ability to Buy Twitter Followers, they are all going to give information that is needed with one simple
tweet.

Once a tweet has been posted, this opens up a huge discussion that invites other followers to join in for
their opinion. Through the information that is received in these informal sessions, a business can make
improvements which will affect how they run their business from here on out. And this could be the way in which the business beats the competition.

Thursday, October 18, 2012

Java : Read / Write Excel file (.xls or .xlsx) using Apache POI


We will see how we can read or write excel file (.xls or .xlsx) using Apache POI. To know more about Apache POI, click here.

You can download latest version of JAR files from http://poi.apache.org/download.html.

In our case we are using Apache POI 3.8. To run below example you will need to download poi-bin-3.8-20120326.zip file from http://poi.apache.org/download.html. You will get below JAR files, add those in your claspath.

  • dom4j-1.6.1.jar
  • xmlbeans-2.3.0.jar
  • poi-3.8-20120326.jar
  • poi-ooxml-3.8-20120326.jar
  • poi-ooxml-schemas-3.8-20120326.jar

Please see the self explanatory Java code.

Thursday, October 4, 2012

Why PreparedStatement is used to prevents SQL Injection?

What is a SQL Injection?

In simple language SQL injection is injecting malicious sql code into the application's sql that may help attacker to retrieve sensitive information like user name / passwords etc OR it can also be used by hackers for login without authentication.

For example, We have a human resource management system, where in employee logs in and can view his / her sensitive information like attendance, salary etc. To log on to system every employee requires username and password. Now suppose below function is used to do authentication.

private boolean isAuthenticate(String userName, String password) {

Statement stat = connection.createStatement();

String query = "SELECT 1 FROM EMPLOYEE WHERE USER_NAME  = '"+userName+"'  AND PASSWORD = '"+password+"';";

ResultSet rset = stat.executeQuery(query);

if (rset.next()) {
return true;
}
else {
return false;
}
}


if the above query fetches result then allow the user to enter into the system else don't allow. You might think that the above process is correct but it's not like that, the above function has a serious flaw. let's see how.


Monday, September 24, 2012

Lucene - Updating index files

Apache Lucene(TM) is a high-performance, full-featured text search engine library written entirely in Java. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform.
Apache Lucene is an open source project available for free download. To know more about Lucene , click here.

In this example we will see how to append to an existing lucene index. We will see how we can update the existing index files with new data.

IndexWriter iwriter = new IndexWriter(directory, analyzer, false, MaxFieldLength.UNLIMITED);

Note the boolean variable - true to create the index or overwrite the existing one; false to append to the existing index. To know more about IndexWriter, see API.

About the example: We will create few text files. Then use our java program to create index and search. Then we will add a new file, update the index and search again.

First we will create few text files in a location lets say "C:\TestLucene\files"


Saturday, September 8, 2012

How to create a Jigsaw puzzle using JSP and Javasacript?


What is Jigsaw puzzle?
A Jigsaw puzzle is a tiling puzzle that requires the assembly of numerous small pieces. Each piece usually has a small part of a picture on it; when complete, a jigsaw puzzle produces a complete picture.

In this article we will see how to create a Jigsaw puzzle using javascript. Initially you will require to cut an image into various pieces, that can be done using a simple java program.

Please see the below Java program that will cut an image into number of pieces for a Jigsaw puzzle. Just provide the desire number of rows and column, it will automatically cut an image into that number of pieces.

Please see the self explanatory Java program below

More Panda and Penguin Updates Expected from Google

It's the high time for all the online business owners to fasten their seat belts and make some necessary improvements in their websites, as Google is planning to give them more jolts with its Panda and Penguin updates. Although recently Google has made updates in the Panda algorithm in the month of July 2012 to trace pages with the low quality web content. This update was minor in nature and no one in the online world noticed it. According to Google head Matt Cutts, ''These updates are majorly aimed at penalizing all the web sites which try to spam the search and try to take a credit for the information which is  completely copied and lacks credibility. In the SES  San Francisco conference on 15th August 2012, he further explained that the Penguin algorithm is still making adjustments and it will not allow sites to get rewarded for the spam as it used to happen in the previous years''. With the help of these updates, all the link exchange as well as linking tricks have now been caught by the the search engine and the sites which have been making  attempts to over optimize the sites will be recognized and punished by the spam fighting team.

Sunday, September 2, 2012

Java / JSP : Simple image cropping example


In this article we will see how to crop an image in Java. You are in this page then u might surely know what exactly the Image cropping is, it is nothing but removal of the outer parts of an image  to improve framing, to change aspect ratio etc.

Image cropping can be implemented easily using Java. First lets see the basic example of image cropping. In the below code we have used getSubimage() function of BufferedImage to achive image cropping feature. No need to add any Jar file directly you can run below code and see the output.

Please see the self explanatory java code below.

Wednesday, August 22, 2012

Java - Image resizing

In this article we will see how to resize a given image to our desire size using Java program. It may be required to resize a large image to 100x100 icon or any other size. It also helps to compress the memory of an image. Image resizing can be required for may reasons - Lets say we want to loan an image in mobile browser, it is not adviceable to load the large image as it is because it may hit page loading time and ofcourse it will create bad experience to end user.

About the example : This is a simple Java program which will resize an image to any other desire size. we have a function resizer() which accepts 4 parameter - Original file, width, height and desire extension. Directly you can run the program and see the out put no need to add any JAR files.

Please see the self explantory program below.

Saturday, August 18, 2012

PHP - Handling File Uploads

In this article we will see how to upload files on PHP web page. You have to set up the form as a multipart form if you want to use file upload controls. In this example, that means you set the <form> element's enctype (encoding type) attribute to "multipart/form-data". You can also set the action attribute to the URL where you want the file data to be sent and the method to "post".

About the example : We have a file fileUploadForm.php, it will be used as a form to browse and upload file and of course it can have other form elements (text, checkbox, radobutton etc) as well. The action attribute is set to URL submitFile.php which will handle the file. It can specify the location where to save the file. Please see the self explanatory example below.


Thursday, August 16, 2012

PHP - Form elements

In this article we will see how to create form in PHP and send data to next PHP page. Like other languages you need to specify the methods with which your data will be sent - "GET" and "POST". If you've used the POST method, you can find that data in the $_POST array similarly if you've used the GET method, you use the $_GET array. These array are "super global" arrays, which means that they're available to you without having to use the global keyword. Also, there is a $_REQUEST array which holds data from both $_GET and $_POST array.

We will create a form which contain various form elements like text box, password, radio button, select dropdown, text area and check box.

Using Twitter To Build Brand Integrity


A company's ability to humanize itself gives its reputation an endearing appeal to the public. High-ranking executives who take time to interact with ground-level clients and customers are assets to a company's marketing and advertising goals.

With the advent of enterprise blogging, companies can now use social media to reach out to their potential customers just by using a social media platform. Twitter is at the forefront of the microblogging trend where people share thoughts and information real-time.

Here are some pointers on how to make the most out of your Twitter account to build a solid relationship with your clients and develop a humanized image of your company:

Be Present and Active For Your Twitter Followers in the UK and around the world

1. Put yourself out there and really share honest, personal information about your company. You are not expected to tweet your own personal issues in your life, but giving your followers real-time updates about company activities will make your business more relatable.


Saturday, August 11, 2012

PHP - Database connectivity


Below are the 6 steps used for PHP database connectivity.


Step 1. Create a connection to the database using mysql_connect() function, which returns a connection object.

Syntax : $con = mysql_connect("localhost","root","password");

Step 2. Select database or schema using mysql_select_db() function

Syntax : mysql_select_db("database_name", $con);

Step 3. Execute the query using mysql_query() function. This function is used to send a query or command to a MySQL connection. It returns result object

Syntax : $result = mysql_query($sql);

Step 4. Looping through results. mysql_fetch_array() function is used to fetch a result row as an associative array, a numeric array, or both.

Syntax : $row = mysql_fetch_array($result)

Step 5. Printing the results. Simply printing the values from result array.

Syntax : echo $row['column1']." ".$row['column2'];

Step 6. Closing the connecting using mysql_close() function.

Syntax : mysql_close($con);


Please see the complete tested code, Save the page with .(dot) php extension e.g. ConnectDatabase.php. Provide correct credentials and see the output.


Friday, August 10, 2012

JavaScript - Simple pagination logic


This article will help you to know how you can create a pagination in any webpage. Here I have used it in JavaScript, of course you can use it in any other language as u wish like Java, PHP, ASP etc.

What is Pagination?

Pagination is nothing but the sequence of numbers assigned to a content in webpage. Lets say if you want to show number of contents in a particular web page, its not recommended to show all of them in a single page instead show specific number of contents in one page followed by next set of content in next page and provide navigation to go through each page. In the same way when we do Google search you can see navigation appears at the bottom of the page to go to the next page.


Please see the self explanatory html code below, no need to have any server directly you can run and see the output

Sunday, July 29, 2012

How to boost your Instagram Followers to increase your social output


The Instagram mobile application is now more popular than ever, behind Pinterest it is the fasting growing social network; now topping 80 million worldwide users.  Not bad considering it’s designed to be a mobile only service.
In order to build large numbers of followers through Instagram, there are some tested and tried techniques that you can use. Unfortunately, as with all things in life – the best route is also the longest route.

Upload better photographs (Simple!)

At first, your only consideration should be the creation of attractive photos. The reason for this is that people have the tendency of following accounts that only present the most relevant and beautiful snaps.  This makes sense and is often lost on marketers who are looking to crack a new social field.  Customers don’t care if you are Nike or Adidas or even Facebook or their favourite football team – they are on Instagram to see photos that they enjoy looking at.

For this reason, you need to come up with a good plan every time you are taking a photo.
Refrain from taking meaningless or trite photos, which many people see every day. According to Nick Bilton who works for the New York Times, (his Instagram account has more than fifty thousand followers)

“people are more likely to follow you for quality over quantity – yes you could take a fancy picture of your starbucks cup but if I don’t know who you are and your photo is generic, I won’t be following you.  The first rule of instagram is – think quality

Publishing excellent and average photos at the same time is not good because the mediocre photos can act as a turn off to your visitors – a user on Instagram is 40% more likely to unfollow you than on twitter as there is less social engagement.

Additionally if you have a large number of attractive photos, it’s advisable to post them in moderation. This is to keep the interest of people following your Instagram account high and they will continue checking your photos regularly.  Think of it like you are telling a great story to your children – you don’t give the story away in the synopsis – you develop the story over time and keep their intrigue.

Tuesday, July 24, 2012

How to use Apache Axis2 for consuming a web service?

About the example:


In this example we will see how to use rather consume a web service using Apache Axis2. We have a Hello World web service which is already published, it accepts a String name and prints Hello name in return. To know more about how to publish a web service, click here.

Below are the steps which shows how to consume a web service using Apache Axis2

1. Download latest version of axis2 files from http://axis.apache.org/axis2/java/core/. (i.e. axis2-1.6.2-bin.zip).


2. Extract the folder (i.e. axis2-1.6.2) in your desire location. Lets assume as C:\axis2-1.6.2.

3. Add enviroment variable AXIS2_HOME and set the value "C:\axis2-1.6.2". Also make sure that JAVA_HOME is set in enviroment variables.

4. Now you can use wsdl2java.bat file from folder "C:\axis2-1.6.2\bin" to download web service stubs. Use command prompt and go to folder C:\axis2-1.6.2\bin and run below command.

   wsdl2java.bat -uri http://localhost:8080/SimpleWebservice/hellows?wsdl

   Note : Provide your wsdl URL in above command, you can also use XSD file instead of wsdl URL. Here we have already published a hello world web services. To know how to publish a simple hello world web service, click here.

   Please see the screen shot below.


Friday, July 6, 2012

Lucene 3.0 example - Indexing and searching database tables


Apache Lucene(TM) is a high-performance, full-featured text search engine library written entirely in Java. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform.
Apache Lucene is an open source project available for free download. To know more about Lucene , click here.

About the example:

Here is the simple java program which will create index files from the data which is fetched from database. And it will perform search from the created index files and display the results. We are using Lucene 3.0 and My SQL. The basics behind is very simple, we will fetch data from database using JDBC (you can use Hibernate or so accordingly) and create index files.

You can store database column(s) in the index files depending upon your requirement. If you want to perform search in one or two column only then no need to add all columns in index files. You can store that particular column and primary key, and perform search on that column and retrieve primary key and use it accordingly.

Creating index is simple and straight forward just add the filed and filed values in Document. Searching can be done in many ways as per requirement, if you want to perform search on one filed then you can use QueryParser, for searching multiple field you can use MultiFieldQueryParser. In query you can use wild card (e.g. DATA*), logical operators (e.g DATA1 OR DATA2) etc.

To run below example please add lucene-core-3.0.2.jar (For Lucene) and mysql-connector-java-5.1.5.jar (For JDBC - My SQL) in your application's classpath.
To download lucene-core-3.0.2.jar, click here.
How to install My SQL, click here.


Tuesday, July 3, 2012

Javascript : On scroll fill data at the end of the page

Other day while browsing facebook, i saw when we scroll to the end of the home page it fills more data without refreshing the whole page. Again when u reach to the end of the page it fetches more data and this continues. I didn't bother to check its upper limit, may be at some point of time it will go out of memory of the browser.

So lets see how this functionality can be achieved. Below javascript variables can be used to detect when user have reached to the end of the body.

  • document.body.scrollTop - scroll bar position
  • document.body.scrollHeight - height of the scroll bar
  • document.body.clientHeight - total height of the body

so if (scrollHeight - scrollTop) is equal to clientHeight you have reached to the end of the body. And obviously you can use various APIs like AJAX, DWR, Ext JS etc to load data without refreshing the whole page.

Below is the standalone tested HTML code, directly you can test this example no need to have any server. Please see the self explanatory html code.


<HTML>

<HEAD>
<TITLE>Scroll Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
divCount = 1;
function onScrollDiv()
{
if((document.body.scrollHeight - document.body.scrollTop) == document.body.clientHeight)
{
onLoadData();
}

return false;
}

function onLoadData()
{
previousCount = divCount;
divCount++;

//Get data using AJAX, DWR, Ext JS etc
htmlData = "<table width='50%' border='1'><tr><td height='200px' align='center'>"+new Date()+"</td></tr></table>";

document.getElementById("div"+previousCount).innerHTML = htmlData;

var newDiv = document.createElement("div");
newDiv.innerHTML = "<div id='div"+divCount+"'>Loading...</div>"
var previousDiv = document.getElementById("div"+previousCount);

insertAfter(newDiv,previousDiv.parentNode);
return false;
}

function insertAfter(new_node, existing_node) {

if (existing_node.nextSibling) {
existing_node.parentNode.insertBefore(new_node, existing_node.nextSibling);
} else {
existing_node.parentNode.appendChild(new_node);
}
}

//-->
</SCRIPT>
</HEAD>
<BODY onload="onLoadData();" onscroll="onScrollDiv();">
<center>
Simple Javascript example which fills data when you scroll at the end of the file same like Facebook
<br />
Resize the window so that scroll bar appears on the right hand side then you can test it.

<div>
<div id="div1"></div>
</div>

</center>
</BODY>
</HTML>

Sunday, July 1, 2012

Spring : MultiActionController Example

Lets create a webproject in My Eclipse (lets say MultiActionController). Now we will add spring Capabilities to it. Here we are using Spring 3.0


(Right click on project) -> My Eclipse -> Add Spring Capabilities..


Adding below libraries (as shown in below image)

  • Spring 3.0 Core Libraries
  • Spring 3.0 Web Libraries


Spring : SimpleFormController Example

Before understanding SimpleFormController you must understand its Spring bean lifecycle. Below diagram tries to explain you the flow of SimpleFormController. 

  • Whenever a request comes from browser it checks in deployment descriptor (i.e Web.xml) for its servlet and url mapping. 
  • Then request goes to its corresponding dispatcher-servlet.xml, The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request in our case its SimpleFormController.
  • The Controller process the request by calling the appropriate service methods i.e isFormSubmitted(). Here you can write your own logic of a form being submitted or not. Usually if a request object is empty its a first time request and it returns false. 
  • formBackingObject() method will be called regardless of form is submitted or not however formBackingObject() method will return FormBean Object to formView when form is not submitted and ModelAndView Object to successView when form is submitted. 
  • Then request goes to a ViewResolver to find the actual View to invoke. The View with the help of the FormBean or ModelAndView will render the result back to the user.



Lets create a webproject in My Eclipse (lets say SpringFormController). Now we will add spring Capabilities to it. Here we are using Spring 2.5


(Right click on project) -> My Eclipse -> Add Spring Capabilities..

Friday, June 29, 2012

JSTL : How to use fmt:message and ResourceBundle

There are two ways you can access values from a property file. Mostly a text value which can change in future are kept in property file and access it using fmt:message and ResourceBundle in JSP and JAVA respectively so that if the text values are changed in future it wont affect our code. We just need to change in property file and rest all will be taken care implicitly.

Lets see how to use fmt:message and ResourceBundle in JSP and JAVA respectively.

1. In JSP

If you need to access the property value in JSP, first lets create a property file lets say prop.properties. Add prop.properties in src folder of your application.

prop.properties

key1=This is value1
key2=This is value2

Add the mapping in web.xml or Spring's dispatcher-servlet.xml as shown below

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="prop" />
</bean>

Note the value="prop" it says to load prop.properties from the src folder. Now through JSP you can access the property by its key as shown below

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<fmt:bundle basename="prop">
<fmt:message key="key1"/>
<fmt:message key="key2"/>
</fmt:bundle>

2. In Java

Also you may need to access these properties in a JAVA program it could be either bean or any controller. You can access using java.util.ResourceBundle as shown below.

String value1 = ResourceBundle.getBundle("prop").getString("key1");
String value2 = ResourceBundle.getBundle("prop").getString("key2");

Note : You may get below error

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/fmt cannot be resolved in either web.xml or the jar files deployed with this application

To solve above error you need to include jstl-1.2.jar in your application's classpath. It could be possible that your application is not able to detect jstl-1.2.jar file.

Javascript : Encode special characters

In Javascript, you may required to escape special characters from a text at some point of time and later you may need to retrieve the original text. This may be because of some logic or for passing as argument in some function. The basic is very simple we will write a encode function which will encode the special characters and a decode function which will get the original text out of encoded text.

Please use the below functions in your code accordingly.

<script language="Javascript">


   var toEncode = new Array(" ","!","@","#","$","%","^","&","*","(",")","-","_","=","+",":","\;",".","\"","'","\\","/","?","<",">","~","[","]","{","}","`");
 var toDecode = new Array("%20","%21","@","%23","%24","%25","%5E","%26","*","%28","%29","-","_","%3D","+","%3A","%3B",".","%22","%27","%5C","/ /","%3F","%3C","%3E","%7E","%5B","%5D","%7B","%7D","%60");

 function encode(val)
 {
  for (var i = 0; i < toEncode.length; i++)
  {
   val = val.replace(toEncode[i],toDecode[i]);
  }
  
  return val;
 }

 function decode(val)
 {
  for (var i = toDecode.length; i >= 0; i--)
  {
   val = val.replace(toDecode[i],toEncode[i]);
  }
  
  return val;
 }

</script>

Monday, June 18, 2012

DWR Hello World example

DWR - Direct Web Remoting

DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible. In simple words DWR is Easy Ajax for Java. Unlike AJAX you don't have to write codes to get XHTML object or check for state change etc. To know more about DWR, click here.

DWR is supported by almost all browsers like Firefox,Internet Explorer,Opera and Safari. To know more, click here.

About the example

We will create a simple java class (i.e HelloWorld.java) with a method sayHello() which will accept a name and print Hello name. We can call this java fuction with JavaScript in a browser. Same as Ajax call without refreshing the whole page.

Below are the steps to run the example.

1. For running the below example you need to add below mentioned JAR file in lib folder of your web project.

  • dwr.jar
  • commons-logging-1.1.1.jar 

For downloading dwr.jar, click here
commons-logging-1.1.1.jar, click here.


2. Add the DWR servlet definition and mapping to your application's web.xml. This is just like defining a normal servlet.


<servlet>
  <display-name>DWR Servlet</display-name>
  <servlet-name>dwr-invoker</servlet-name> 
  <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
  <init-param>
     <param-name>debug</param-name>
     <param-value>true</param-value>
  </init-param>
</servlet>
 
<servlet-mapping>
  <servlet-name>dwr-invoker</servlet-name>
  <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>

Monday, May 21, 2012

iCal4j example - Set a Meeting using iCalendar

iCalendar is a computer file format which allows Internet users to send meeting requests and tasks to other Internet users, via email, or sharing files with an extension of .ics. Recipients of the iCalendar data file (with supporting software, such as an email client or calendar application) can respond to the sender easily or counter propose another meeting date/time.

iCalendar is used and supported by a large number of products, including Google Calendar, Apple iCal,IBM Lotus Notes,Yahoo Calendar, Microsoft Outlook etc

iCal4j is an API which is used to modifying existing iCalendar data or creating new iCalendar data. To know more about iCal4j, click here.

About the example

This example is straight forward, we will create a calendar (net.fortuna.ical4j.model.Calendar) object and add a Meeting event to it. You can set various properties to the event like subject, location, description etc. Obviously you can customize it according to your requirement. This example will generate a .ics file (TestCalendar.ics). You can send this generated file via email to interested parties. Please see the below self explanatory java program.

For running below example you will need to add below mentioned JAR files in your classpath.
  • ical4j-1.0.3.jar
  • backport-util-concurrent-3.1.jar
  • commons-logging-1.1.1.jar
  • commons-lang-2.6.jar

To download the above JAR file, click here.