Connecting to mysql database

Below is the code for creating mysql connection in java and php.
Please make sure that mysql-connector-java-5.0.6-bin.jar is in class path.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySqlConnectionTest {
    public static void main(String[] args) {
        Connection connection = null;

        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            // We want to connect to a database name 'test' in mysql.
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");

            if (!connection.isClosed()) {
                System.out.println("Successfully connected to MySQL server...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
           } catch (SQLException e) {
       }
    }
  }
}

Below is the code in php for mysql connection.

<?php
    $hostname='localhost'; //// specify host
    $user='root'; //// database user name
    $password='root'; //// database password
    $database='test'; //// database name
    $connection = mysql_connect("$hostname" , "$user" , "$passwprd")
    or die ("Unable connect to MySQL");
    $db = mysql_select_db($database , $connection) or die ("Can't find database.");
?>

How to prevent browser caching

There are many ways you can prevent browser caching.
One of them is to include following meta tags, place these tags in head section of html document.

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">

For ASP pages use following script at the extreme beginning of the page

<% Response.CacheControl = "no-cache" %>
<% Response.AddHeader "Pragma", "no-cache" %>
<% Response.Expires = -1 %>

In case of JSP pages use following code

<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", -1);
%>

If you are generating your response in java or some other languages then you need to set following parameters in response header.

response.addHeader("cache-control", "no-cache");
response.addHeader("pragma", "no-cache");
response.addHeader("expires", "-1");

All of the above method works on the response of the particular page and tell browser not the cache the response.

There is another way of telling browser to make a fresh request and don’t use the cached content for the page if any. This is done by appending some random characters to requested url. Below is sample code

<script>
var url = "http://techpitcher.com";
url += "?preventCache="+ Math.floor(Math.random()*100000);
</script>

This will create a random url every time and won’t allow browser to use cache content.

Static in java

A class is the blueprint from which individual objects are created. We won’t get anything until we create an object of that class with new and at that point we get space of data storage and handle (method) for this data.
There are two cases which don’t fit in above situation. One we want only one storage of data for every object or even if no object is created. The second situation is that if we want a method that is not associated with any object. Method is directly associated with the class and operate on class data (static) only.
We can achieve both by static keyword. When we say variable or method static that means it is related with class and every instance will access same copy.
If a method is declared static then we can use only static data member inside it. Static method in super class can be overridden by static method in sub-class only. However we can’t override a static method with non-static method. Static method is implicitly final.
It is not recommended to use instance name for accessing static data or method since this gives a feeling that data or method is associated with object and not with the class. But that is not the case.

Generating jasper report in xls

Below is the code for generating report in xls by using jasper framework.

List dataList = new ArrayList();
Map productMap = new HashMap();
productMap.put("product_id", "1001");
productMap.put("product_name", "Product 1");
dataList.add(productMap);
productMap = new HashMap();
productMap.put("product_id", "1002");
productMap.put("product_name", "Product 2");
dataList.add(productMap);
JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(dataList);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,  new HashMap(), jrBeanCollectionDataSource);
OutputStream ouputStream = new FileOutputStream(new File("C:/JasperReports/prod_detail.xls"));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, byteArrayOutputStream);
ouputStream.write(byteArrayOutputStream.toByteArray());
ouputStream.flush();
ouputStream.close();

Access is denied (user is not anonymous)

DEBUG org.acegisecurity.ui.ExceptionTranslationFilter - Access is denied (user is not anonymous);
delegating to AccessDeniedHandlerorg.acegisecurity.AccessDeniedException: Access is denied
at org.acegisecurity.vote.AffirmativeBased.decide(AffirmativeBased.java:68)
at org.acegisecurity.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:292)
at org.acegisecurity.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:104)
at org.acegisecurity.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:72)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:110)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:142)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:81)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:229)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:106)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:286)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:149)
at org.acegisecurity.util.FilterToBeanProxy.doFilter(FilterToBeanProxy.java:98)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)

As exception itself says that “Access is denied (user is not anonymous)” i.e. authorities are granted to Authentication object and the value of this authority is not anonymous. The authorities granted to Authentication object doesn’t have permission to access the required resource.
It can be corrected by granting access to the required resource. The application must be having roles mapping on different resources e.g.

<property name="objectDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/images/**=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR,ROLE_OTHER
/css/**=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR,ROLE_OTHER
/js/**=ROLE_ANONYMOUS,ROLE_ADMINISTRATOR,ROLE_OTHER
/ws/**=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR,ROLE_OTHER
</value>
</property>

If you look carefully in above configuration then js folder doesn’t allow access to files inside js for ROLE_OWNER. If a user having role ROLE_OWNER logs into the system and tries to access resource inside js folder then he’ll get above exception as user is not anonymous and is not allowed to access this resource.
To fix this problem allow js accessible to ROLE_OWNER.

What is an abstract class?

You create an abstract class when you want to manipulate a set of classes through this common interface. All derived-class methods that match the signature of the base-class declaration will be called using the dynamic binding mechanism.
A class containing abstract methods is called an abstract class. Class does not contain implementation for Abstract methods. If a class contains one or more abstract methods, the class itself must be qualified as abstract. (Otherwise, the compiler gives you an error message.)