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.)
Describe OOPs concepts in Java
The four main concepts are involved in OOP:
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Abstraction
Abstraction is hiding of information from others. In case of Java, its hiding implementation of a method/ object. For example if an interface is available to outer world, so end user won’t know about implementing class details. This is just a kind of abstraction. Abstraction could be anywhere in java, wherever we hide some information, we call it abstraction.
Encapsulation
Encapsulation is combining data and method along with implementation hiding within the class. Implementation hiding is done with the help of access modifiers (public, protected, package, private).
Inheritance
Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. Although inheritance may sometimes imply (especially in Java, where the keyword for inheritance is extends) that you are going to add new methods to the interface, that’s not necessarily true. The second and more important way to differentiate your new class is to change the behavior of an existing base-class method. This is referred to as overriding that method.
Polymorphism
Polymorphism is something like one name many forms. Polymorphism is also known as dynamic binding or late binding or run-time binding.
What is watchdog timer?
Watchdog timer is hardware circuitary tightly integrated into embedded systems’ CPU to have a watch on embedded system’s working. It has ability to detect if embedded system is entered into a hanged state. It then resets the embedded system so that it doesn’t remain in hanged state indefinately. Watchdog timer is generally used in embedded systems where their is no human intervention present to reset it when system hangs. As its name suggests watchdog timer is a timer circuitary which keeps on counting and expires until reset. Embedded system software is expected to restart the timer regularly to prevent it from expiring under normal conditions. When systems hangs the timer is not restarted and it expires to give an indication to the system to restart.
jQuery - A lightweight JavaScript Library
jQuery is JavaScript library that simplifies lots of work done in JavaScript. jQuery makes HTML document traverse easy. It can provide ajax support to your website. There are lots of site which provides jQuery plugins (plugin for validation, animation, cookies, events). The most important point to remember is that by using jQuery you can easily get multiple browser compatibility.
There are three downloads available
1. Minified and Gzipped (Used in production)
2. Packed version (This version is not gzipped)
3. Uncompressed (Used in testing and learning)
Reference
http://jquery.com
The Constructor Date(String) is Deprecated since of JDK 1.1 you should not use it
You should use java.text.SimpleDateFormat to convert String value to Date. E.g.
private static final SimpleDateFormat sdf = new SimpleDateFormat(”yyyy-MM-dd”); String birthDate = “1981-12-30?; Date birth = sdf.format(birthDate);