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.