Pages

Monday, July 30, 2012

PostgreSQL create table if not exists


Try running a query on the table. If it throws an exception then catch the exception and create a new table.
try {
    int a =  db.queryForInt("SELECT COUNT(*) FROM USERS;");
}
catch (Exception e) {
    System.out.print(e.toString());
    db.update("CREATE TABLE USERS (" +
                "id SERIAL," +
                "PRIMARY KEY(id)," +
                "name varchar(30) NOT NULL," +
                "email varchar(30) NOT NULL," +
                "username varchar(30) NOT NULL," +
                "password varchar(30) NOT NULL" +
                ");");
}
return db;

Wednesday, July 25, 2012

Example of Log4J

Log4J Example:

@Controller
public class VanityController {
    private static Logger logger = Logger.getLogger(VanityController.class.toString());

    @RequestMapping(value= "/user/{vanity}", method = RequestMethod.GET)
    public ModelAndView viewProfile(@PathVariable String vanity) {
        ModelAndView mv = new ModelAndView("vanity");
        logger.info(vanity + "vanity called!");
        mv.addObject("name", vanity);
        return mv;
    }

}

when called localhost:8080/user/todo
this is what was displayed in the output: 
INFO: todovanity called!

Adding Log4J dependency to Maven


<dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
      <scope>runtime</scope>
   </dependency>

Tuesday, July 24, 2012

FATAL: password authentication failed for user postgres


If you face this error on trying to use psql, the following steps should fix it:

By default, postgres creates a user named 'postgres'. We log in as postgres, and give a password.

$ sudo -u postgres psql
\password
Enter password: ...
...

Now try again. The above steps work for a fresh install of postgres 9.1 and 8.4 on Ubuntu 12.04.

Thursday, July 19, 2012

Installing postgresql in Ubuntu and configuring it with your SpringFramework application


Installation sudo apt-get install postgresql
Installing the GUI interface sudo apt-get install pgadmin3

Starting psql on command line: sudo -u postgres psql postgres
                                                                  username       dbname

postgres is the user/admin which is there by default.
Also you can this on the command line to start psql: psql -u postgres -h localhost

Creating a new db  sudo -u postgres createdb mydb1 or you can use the GUI to add a new db. 

Starting psql for your db sudo -u postgres psql mydb1

Time to configure postgresql to your Spring application, we assume that you are using Maven as the build tool.

Add the following dependency in your pom.xml
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>

But before this make sure you check the version of your postgres by writing on the command line
psql --version, the above code is valid if your version is 9.1.4 else go here http://mvnrepository.com/artifact/postgresql/postgresql/ and add the dependency to your pom.xml accordingly. 
            


Checking that your code is working by creating a connection to the Database. If the following code does not give any error then you have a reason to celebrate. Make sure to add the try and catch blocks wherever necessary.

  Class.forName("org.postgresql.Driver");

  Connection connection = DriverManager.getConnection(
                    "jdbc:postgresql://127.0.0.1:5432/mydb1", "postgres",
                    "crossword");


Now we need to add a Configuration file in our SpringFramework that will have the configuration for the datasource to connect to postgres. Your configuration will have the following datasource:

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl("jdbc:postgresql://127.0.0.1:5432/mydb1");
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUsername("postgres");
        dataSource.setPassword("crossword");
        SimpleJdbcTemplate db = new SimpleJdbcTemplate(dataSource);


After making these changes this is the commit:
https://github.com/gauravmunjal/HelloWorldSpring/commit/51041b61b7230816175e53fe47b78132fd762f39

References 

Wednesday, July 18, 2012

Using Springframework in Idea Intellij with Maven Build Tool


  • Create a new Project from Scratch
  • Select the Maven Module
    • Maven allows a project to build using its project object model (POM) and a set of plugins that are shared by all projects using Maven, providing a uniform build system. Once you familiarize yourself with how one Maven project builds you automatically know how all Maven projects build saving you immense amounts of time when trying to navigate many projects.
  • Add the following dependencies to your pom.xml
  • <dependencies>
            <dependency>
                <groupId>commons-dbcp</groupId>
                <artifactId>commons-dbcp</artifactId>
                <version>1.4</version>
            </dependency>
            <dependency>
                <groupId>com.google.collections</groupId>
                <artifactId>google-collections</artifactId>
                <version>1.0</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>3.0.5.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>3.0.5.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>cglib</groupId>
                <artifactId>cglib</artifactId>
                <version>2.2.2</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>1.5.3</version>
            </dependency>
            <dependency>
                <groupId>org.hsqldb</groupId>
                <artifactId>hsqldb</artifactId>
                <version>2.0.0</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            </dependency>
        </dependencies>
  • Build configuration in pom.xml
  • <build>

        <finalName>YourApplicationName</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>7.4.2.v20110526</version>
                <configuration>
                    <scanIntervalSeconds>1</scanIntervalSeconds>
                </configuration>
            </plugin>
        </plugins>
    </build>

  • In the java package create a new package with your desired name and then add three more packages namely controllers, model and services
  • In the main directory create a directory webapp and in it create two directories static and WEB-INF
  • In the WEB-INF directory add a new directory 'jsp' and in it create a jsp file 
  • Also the WEB-INF Directory should have two more files dispatcher-servlet.xml and web.xml 
  • dispatcher-servlet.xml
<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven/>

    <context:component-scan base-package="SampleApp"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>
  • web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID"
         version="2.5">
    <display-name>Archetype Created Web Application</display-name>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/static/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

After doing the same, just compile your code using Maven and run the Jetty server whose dependency was added in the pom.xml file. Here is the link to the public repository for the same: https://github.com/gauravmunjal/HelloWorldSpring