Java Spring FrameWork

From Objectif Client Inc
Jump to navigation Jump to search

Notes

Rest Architecture

REST (REpresentational State Transfer) New naming : HATEOAS (Hypermedia as the Engine of Application State)

  1. Client-serveur: Data remain on serveur and client is a separated entity
  2. No state: Each request provide to the server all the necessary information to provide the service
  3. Cache: The information sent by the server must contain, creation date, expiration date.
  4. Uniform Interface:
    1. Each resources has a unic Id;
    2. Resources have representation defined;
    3. Auto descriptive message: The content and how to read the message; (Like how the message is coded Utf8).
    4. Hypermedia Each access to the next step of the application is describe in the current message.
  5. Hyercharchie
  6. Code-on-Demande(facultative): Script excecution on the client retreived from the server.


| Stackoverflow what exactly is restful programming

Maven Setup

<!-- General repository to get package -->  
<repositories>
    <repository>
        <id>io.spring.repo.maven.release</id>
        <url>http://repo.spring.io/release/</url>
        <snapshots><enabled>false</enabled></snapshots>
    </repository>
</repositories>

<!-- Maven bom to manage dependencies between jar -->  
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.1.2.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<!-- Dependencies without version because they are managed by Maven Bom --> 
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>
</dependencies>

Setup

web.xml

1 In the web.xml specify the location of the Spring Configuration File

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         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">

<!-- Application Name (for Information only) -->
    <display-name>Spring MyApp</display-name>
    <description>MyApp with Spring FrameWork</description>

<!-- A context listner to load other spring context xml file -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

<!-- Context Config File Location (where are located the configuration file) -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
    </context-param>

<!-- Handles Spring requests -->
    <servlet>
        <servlet-name>myapplication</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/spring/webmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>myapplication</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

<!-- timeout Setting -->
    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>


<!-- Error page Management java error and page no found 404  -->
    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/uncaughtException</location>
    </error-page>
    
    <error-page>
        <error-code>404</error-code>
        <location>/resourceNotFound</location>
    </error-page>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <!--
        This will automatically locate any and all property files you have
        within your classpath, provided they fall under the META-INF/spring
        directory. The located property files are parsed and their values can
        then be used within application context files in the form of
        ${propertyKey}.
    -->
    <context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
    <!--
        Turn on AspectJ @Configurable support. As a result, any time you
        instantiate an object, Spring will attempt to perform dependency
        injection on that object. This occurs for instantiation via the "new"
        keyword, as well as via reflection. This is possible because AspectJ
        is used to "weave" Roo-based applications at compile time. In effect
        this feature allows dependency injection of any object at all in your
        system, which is a very useful feature (without @Configurable you'd
        only be able to dependency inject objects acquired from Spring or
        subsequently presented to a specific Spring dependency injection
        method). Roo applications use this useful feature in a number of
        areas, such as @PersistenceContext injection into entities.
    -->
    <context:spring-configured/>
    <!--
        This declaration will cause Spring to locate every @Component,
        @Repository and @Service in your application. In practical terms this
        allows you to write a POJO and then simply annotate the new POJO as an
        @Service and Spring will automatically detect, instantiate and
        dependency inject your service at startup time. Importantly, you can
        then also have your new service injected into any other class that
        requires it simply by declaring a field for your service inside the
        relying class and Spring will inject it. Note that two exclude filters
        are declared. The first ensures that Spring doesn't spend time
        introspecting Roo-specific ITD aspects. The second ensures Roo doesn't
        instantiate your @Controller classes, as these should be instantiated
        by a web tier application context. Refer to web.xml for more details
        about the web tier application context setup services.
        
        Furthermore, this turns on @Autowired, @PostConstruct etc support. These 
        annotations allow you to use common Spring and Java Enterprise Edition 
        annotations in your classes without needing to do any special configuration. 
        The most commonly used annotation is @Autowired, which instructs Spring to
        dependency inject an object into your class.
    -->
    <context:component-scan base-package="com.objclt.myapp">
        <context:exclude-filter expression=".*_Roo_.*" type="regex"/>
        <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
    </context:component-scan>

    <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
        <property name="driverClassName" value="${database.driverClassName}"/>
        <property name="url" value="${database.url}"/>
        <property name="username" value="${database.username}"/>
        <property name="password" value="${database.password}"/>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="true"/>
        <property name="testWhileIdle" value="true"/>
        <property name="timeBetweenEvictionRunsMillis" value="1800000"/>
        <property name="numTestsPerEvictionRun" value="3"/>
        <property name="minEvictableIdleTimeMillis" value="1800000"/>
        <property name="validationQuery" value="SELECT 1"/>
    </bean>

    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
        <property name="persistenceUnitName" value="persistenceUnit"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

applicationContext-jpa.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/data/jpa"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <repositories base-package="com.objclt.myapp" />

</beans:beans>

applicationContext-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" 
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    <!-- HTTP security configurations -->
    <http auto-config="true" use-expressions="true">
        <form-login login-processing-url="/resources/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t" />
        <logout logout-url="/resources/j_spring_security_logout" />
        <!-- Configure these elements to secure URIs in your application -->
        <intercept-url pattern="/choices/**" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/member/**" access="isAuthenticated()" />
        <intercept-url pattern="/resources/**" access="permitAll" />
        <intercept-url pattern="/login/**" access="permitAll" />
        <intercept-url pattern="/**" access="isAuthenticated()" />
    </http>
    <!-- Configure Authentication mechanism -->
    <authentication-manager alias="authenticationManager">
        <!-- SHA-256 values can be produced using 'echo -n your_desired_password | sha256sum' (using normal *nix environments) -->
        <authentication-provider>
          <!--  <password-encoder hash="sha-256" /> -->
         <!--   <user-service> -->
          <!--      <user name="admin" password="8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" authorities="ROLE_ADMIN" /> -->
          <!--      <user name="user" password="04f8996da763b7a969b1028ee3007569eaf3a635486ddab211d512c85b9df8fb" authorities="ROLE_USER" /> -->
          <!--  </user-service> -->
              <jdbc-user-service data-source-ref="dataSource"
                  users-by-username-query="SELECT U.User AS username, U.Password as password, U.Status as enabled FROM User U where U.User=?"
             authorities-by-username-query="SELECT U.User as username, R.role as authority FROM User U left join User_Role UR on U.id = UR.User_Id  left join Role R on R.id = UR.Role_id WHERE U.User=?" />
        </authentication-provider>
    </authentication-manager>
</beans:beans>

database.properties

# Properties file with JDBC and JPA settings.
#
# Applied by <context:property-placeholder location="jdbc.properties"/> from
# various application context XML files (e.g., "applicationContext-*.xml").
# Targeted at system administrators, to avoid touching the context XML files.

#-------------------------------------------------------------------------------
# HSQL Settings

#jdbc.driverClassName=org.hsqldb.jdbcDriver
#jdbc.url=jdbc:hsqldb:mem:exotest
#jdbc.username=sa
#jdbc.password=

# Properties that control the population of schema and data for a new data source
#jdbc.initLocation=classpath:db/hsqldb/initDB.sql
#jdbc.dataLocation=classpath:db/hsqldb/populateDB.sql

# Property that determines which database to use with an AbstractJpaVendorAdapter
#jpa.database=HSQL

#jpa.showSql=true

#-------------------------------------------------------------------------------
# MySQL Settings

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydatabase
jdbc.username=root
jdbc.password=

# Properties that control the population of schema and data for a new data source
#jdbc.initLocation=classpath:db/mysql/initDB.sql
#jdbc.dataLocation=classpath:db/mysql/populateDB.sql

# Property that determines which Hibernate dialect to use
# (only applied with "applicationContext-hibernate.xml")
hibernate.dialect=org.hibernate.dialect.MySQLDialect

# Property that determines which database to use with an AbstractJpaVendorAdapter
jpa.database=MYSQL

jpa.showSql=false