Friday, December 23, 2016

RCU:6107 DB Init Param error

RCU:6107 DB Init Param error


While Installing Repository Creation Utility (RCU) Installation the following error occurs:
RCU:6107 DB Init Param Error
This can be removed simply by the following:
1. Login on your database with system user.
2. Write > show parameters processes (which will show the current value of processes).
3. If its value is less than 500 then write the following command:
ALTER SYSTEM SET PROCESSES=500 SCOPE=SPFILE;
4. Write > show parameters open_cursors (which will show the current value of open_cursors).
5. If its value is less than 500 then write the following command:
ALTER SYSTEM SET OPEN_CURSORS=500 SCOPE=SPFILE;
6. Restart your DB or system.
7. Start the installation now….
There will be no error…..

source: https://mhabib.wordpress.com/2010/07/20/rcu6107-db-init-param-error/

Thursday, December 1, 2016

Javascript - JSP not able to find .js file.

I was trying to create a simple web project and was starting to learn JavaScript.
I was suggested to created all JS functions in a .js file and import in to the JSP file, so as the code will be clean and it would be best practise.

But I was facing some issues when I did the following.
<script type="text/javascript"  src="/js/index.js"></script>

This is what I tried. The issue I faced is that my script is not running, which means that the .js file is not being found at runtime.


After some googling, I came to know that I should use like below.
<script type="text/javascript"  src="${pageContext.request.contextPath}/js/index.js"></script>




Explanation given on the internet:

Put the JS file in a folder under web content (but not WEB-INF) like [WebContent]/js/jsgl.min.js, and use the following in the JSP:
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jsgl.min.js"></script>

Explanation
JSP files are compiled by the server, then processed to send data (typically HTML) back to the web browser. A <script> tag is a HTML tag that gets interpreted by the browser, not by the servlet container. So the browser sees that in the HTML then makes a new request to the server for the JavaScript file in the src attribute.
The src attribute is relative to the URL that the browser asked for, not to the path of the JSP on the server.
So as an example, let's say:
  • The browser asks for a page at http://example.com/SomeWebApp/some-resource
  • The servlet container internally forwards the request to a JSP at /WEB-INF/jsp/somepage.jsp
  • The response sent to the browser contains the script tag <script type="text/javascript" src="./jsgl.min.js"></script> (as in your question)
  • The browser sees the URL ./jsgl.min.js and resolves it relative to the URL it has asked the server for (which in this case was http://example.com/SomeWebApp/some-resource - note there is no trailing '/') so the browser will request the JS file from http://example.com/SomeWebApp/jsgl.min.js*. This is because the relative URL in the script tag's src attribute starts with a '.'.
Another answer suggested putting the JS file in a 'js' folder and changing the script tag to <script type="text/javascript" src="/js/jsgl.min.js"></script>. Using the same original page URL as in the example above, the browser would translate this src URL to http://example.com/js/jsgl.min.js. Note that this is missing the "/SomeWebApp" context path.

The best solution therefore is indeed to put the JS file in a static folder like /js/jsgl.min.js, but to use the following in the JSP script tag:
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jsgl.min.js"></script>

The JSP will translate the ${pageContext.request.contextPath} bit into the current context path, making the code portable (if you redeploy the webapp with a different context path, it will still work). So the HTML response received by the browser will be (again, sticking with our example above):
<script type="text/javascript" src="/SomeWebApp/js/jsgl.min.js"></script>
The browser will now resolve that relative URL to the correct targe

Sunday, November 20, 2016

Injecting Spring Beans into Java Servlets

If you are working in a Java Web Application and you are using Spring IoC Container in your application, there is a chance that you might have to inject Spring Beans into a Java Servlet.
Comparing with general spring injection, with Servlet it will be differ. Because servlet will initialized when init method will be excuted. And spring context file will be loaded before all servlets initialization using web.xml. Even if initialize servlets with Spring configuration it will be overrided by init method of servlet.
Now will see process of Injecting Spring Beans into Java Servlets
Goal: What I am trying to achive here retrieving the values from pojo in servlet based on spring injection to display.

Address.java

package com.javavillage.beans;

import org.springframework.stereotype.Component;

@Component
public class Address {
 private String location="Mount Road";
 private String city="Chennai";
 public String getLocation() {
  return location;
 }
 public void setLocation(String location) {
  this.location = location;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
}

applicationContext.xml
In spring context file need to be observed below points.
   context:component-scan:  To enable annotations on specific package.
   context:annotation-config:  To enable annotations.
   context:spring-configured:  To enable Configurable annotation.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:util="http://www.springframework.org/schema/util"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util
  http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 
 <context:component-scan base-package="com.javavillage.beans"></context:component-scan>
 <context:annotation-config/>
 <context:spring-configured/>
 <bean id="address" class="com.javavillage.beans.Address">
  <property name="location" value="Hinjewadi"></property>
  <property name="city" value="Pune"></property>
 </bean>
 
</beans>
TestServlet.java
In TestServlet file need to be observed below points.
   @Configurable:  Marks a class as being eligible for Spring-driven configuration..    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this):  To enable autowire support on current class; as servlet will
   be initialized in init method, added using SpringBeanAutowiringSupport.
package com.javavillage.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.javavillage.beans.Address;

/**
 * Servlet implementation class TestServlet
 */
@Configurable
public class TestServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 
 @Autowired
 private Address address;

 @Override
 public void init(ServletConfig config) throws ServletException{
  super.init(config);
  SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
  
 }
    /**
     * Default constructor. 
     */
    public TestServlet() {
     //
    }
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, 
  *    HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) 
 throws ServletException, IOException {
         
        PrintWriter out=response.getWriter();
        out.println("<br>Name: "+address.getCity());
        out.println("<br>Designation: "+address.getLocation());
        out.close();  
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
  // TODO Auto-generated method stub
 }
}
web.xml
Configured TestServlet in web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

 <display-name>Archetype Created Web Application</display-name>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 
 <servlet>
  <servlet-name>TestServlet</servlet-name>
  <servlet-class>com.javavillage.servlet.TestServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>TestServlet</servlet-name>
  <url-pattern>/TestServlet</url-pattern>
 </servlet-mapping>

</web-app>

pom.xml:
(jar entries for the application)
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>1.7.5</version>
  </dependency>

  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>1.7.5</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>3.0.5.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>3.0.5.RELEASE</version>
  </dependency>
  <dependency>
   <artifactId>spring-web</artifactId>
   <groupId>org.springframework</groupId>
   <version>3.0.5.RELEASE</version>
  </dependency>
  <dependency>
   <artifactId>spring-context</artifactId>
   <groupId>org.springframework</groupId>
   <version>3.0.5.RELEASE</version>
  </dependency>
  <dependency>
   <artifactId>spring-core</artifactId>
   <groupId>org.springframework</groupId>
   <version>3.0.5.RELEASE</version>
  </dependency>
  <dependency>
   <artifactId>spring-beans</artifactId>
   <groupId>org.springframework</groupId>
   <version>3.0.5.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>3.0.5.RELEASE</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aspects</artifactId>
   <version>3.1.2.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.7.4</version>
  </dependency>
Application Project Structure


After execution see below window for servlet with spring injection


If you face any problem with server startup because of amy class missing even after adding all jars, check Deployment Assembly. If you are not able to see Deployement Assembly in eclipse, add all the jars as per below screen. Problem will get resolved.
Double click on Tomcat server in server tab--> open launch Configuration--> Go to Class path tab add all the jars.


Source:http://www.javavillage.in/spring-ioc-on-servlets.php

Sunday, October 30, 2016

Value object & Entity object in Hibernate mapping

Value object & Entity object in Hibernate mapping

Lets consider the following example

Hibrenet-


In Above table the type of fields of the class STUDENT CLASS is as below.
              ID            is INTEGER type
              Name          is VARCHAR type
              DEPARTMENT    is VARCHAR type
              ADDRESS       is VARCHAR type
              COLLEGE       is VARCHAR type
Now what if one of these member variable is an object instead of a simple data type. For example

Hibrenet-intro

Here STUDENT CLASS have a field Address object, this means in the database there are no meaning for Address object, as this Address object in turn have four other fields like.
1. Street
2. City
3. State
4. Pin code
Now the question is how can we save this address object into the database.

Value object


One way of saving the Address Object is to treat the member variable of address objects as the member variable of Student object itself.

Hibrenet-introduction

Here without having a Student object the use of Address object doesn’t make any sense. So the purpose of address object is just provide value to the Student object; And this is what differentiate an Entity object from a Value object.
So what the heck is Value object?

Entity object is the one which have meaning on its own, where a value object has no meaning on its own, the value object belongs to an entity instance and its persistent state is embedded in the table row of the owning entity.
In the above example the Student object represents an Entity object and Address object represents a Value object.
Long story short here:

Entity Object: Has its own database identity (Student table)
Value Object: Doesn’t not have its own database identity

Now let’s create an class for Address (Value object)
package entity;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class Address {
        @Column(name = "STREET_NAME")
        private String street;
        @Column(name = "CITY_NAME")
        private String city;
        @Column(name = "STATE_NAME")
        private String state;
        @Column(name = "PIN_CODE")
        private String pincode;
        
        // Create getters and setters
}

Now in order to make this class of value type, and in order to tell hibernate not to create a separate table for address class, I have used @Embeddable annotation in the Address class, Also we need to use @Embedded annotation in the member variable of Address object in Student entity class as shown below.
package entity;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "STUDENT")
public class Student {

        @Id
        @GeneratedValue
        @Column(name = "ID")
        private int id;

        @Column(name = "NAME")
        private String name;

        @Column(name = "DEPARTMENT")
        private String department;

        @Column(name = "COLLEGE")
        private String college;

        // For value type object
        @Embedded
        private Address address;

       // Getters and Setters
}

Hibernate Configuration file


File: hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">
                 oracle.jdbc.driver.OracleDriver
        </property>
        <property name="hibernate.connection.username">system</property>
        <property name="hibernate.connection.password">admin</property>
        <property name="hibernate.connection.url">
                jdbc:oracle:thin:@127.0.0.1:1521:XE
        </property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

        <!-- Echo all executed SQL to sysout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hibernate.hbm2ddl.auto">create</property>
        <!-- Map Entity Class -->
    <mapping class="entity.Student"></mapping>
</session-factory>
</hibernate-configuration>

HibernateTest class


Create the Main class to run the example.
package util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import entity.Address;
import entity.Student;
public class HibernateUtil {

        public static void main(String[] args) {

                Configuration cf = new Configuration().configure("hibernate.cfg.xml");

                StandardServiceRegistryBuilder srb = 
                         new StandardServiceRegistryBuilder();
                srb.applySettings(cf.getProperties());
                ServiceRegistry sr = srb.build();
                SessionFactory sf = cf.buildSessionFactory(sr);

                Session session = sf.openSession();
                Transaction tx = session.beginTransaction();

                Student student = new Student(); 

                student.setName("Lahir Nisha");
                student.setDepartment("ECE");
                student.setCollege("SKCET");

                Address address1 = new Address();
                address1.setStreet("Race cource");
                address1.setCity("Coimbatore");
                address1.setState("Tamilnadu");
                address1.setPincode("642001");
                student.setAddress(address1);
                session.save(student);  

                tx.commit(); 
                session.close();
                sf.close();
        }
}

Run it – Eclipse Console


Vlue object

Database Output


Vlue object saving

@AttributeOverride annotation:


So far we have seen that an Entity Type Object Student has a Value Object(or Embeddable Object ) ADDRESS with corresponding fields name street, city, pin-code and state save to the database table STUDENT with value object’s column name (CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME).

Suppose in the above scenario if a Student have two addresses like Local Address and Permanent Address then how to manage the column names of these two value objects in the database table STUDENT.

In order to overcome this problem, we have to override the Attribute name of the Value objects. Hibernate has provided @AttributeOverride annotation for this purpose.

Example:-
Student.java

package entity;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "STUDENT")
public class Student {

        @Id
        @GeneratedValue
        @Column(name = "ID")
        private int id;

        @Column(name = "NAME")
        private String name;

        @Column(name = "DEPARTMENT")
        private String department;

        @Column(name = "COLLEGE")
        private String college;

        @Column(name = "ADDRESS")
        @Embedded
        @AttributeOverrides({
           @AttributeOverride(name = "street", column = @Column(name = "HOME_STREET_NAME")),
           @AttributeOverride(name = "city", column = @Column(name = "HOME_CITY_NAME")),
           @AttributeOverride(name = "state", column = @Column(name = "HOME_STATE_NAME")),
           @AttributeOverride(name = "pincode", column = @Column(name = "HOME_PIN_CODE")) })
        private Address homeAddress;

        @Embedded
        private Address permanentAddress;
        // Create getters and setters 
}

HibernateTest class


Create the Main class to run the example.
package util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import entity.Address;
import entity.Student;
public class HibernateUtil {

        public static void main(String[] args) {

                Configuration cf = new Configuration().configure("hibernate.cfg.xml");

                StandardServiceRegistryBuilder srb 
                             = new StandardServiceRegistryBuilder();
                srb.applySettings(cf.getProperties());
                ServiceRegistry sr = srb.build();
                SessionFactory sf = cf.buildSessionFactory(sr);

                Session session = sf.openSession();
                Transaction tx = session.beginTransaction();
                
                Address homeAddress = new Address(); 
                homeAddress.setStreet("Race cource");
                homeAddress.setCity("Coimbatore");
                homeAddress.setState("Tamilnadu");
                homeAddress.setPincode("642001");
                
                Address permanantAddress = new Address();
                permanantAddress.setStreet("Besant nagar");
                permanantAddress.setCity("Chennai");
                permanantAddress.setState("Tamilnadu");
                permanantAddress.setPincode("600001");
                
                Student student = new Student(); 

                student.setName("Lahir Nisha");
                student.setDepartment("ECE");
                student.setCollege("SKCET");
                student.setPermanentAddress(permanantAddress);
                student.setHomeAddress(homeAddress);

                session.save(student); 
        
                tx.commit(); 
                session.close();
                sf.close();
        }
}

Eclipse console after running this program



Hibernate: insert into STUDENT (COLLEGE, DEPARTMENT, HOME_CITY_NAME, HOME_PIN_CODE, HOME_STATE_NAME, HOME_STREET_NAME, NAME, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME, ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)


Source: http://www.simplecodestuffs.com/value-object-entity-object-in-hibernate-mapping/