2014년 3월 21일 금요일

java.io.EOFException: No content to map to Object due to end of input


Server Side

@RequestMapping (value="url",method=RequestMethod.GET)
public @ResponseBody String sampleMethod (@RequestBody String json){

     ObjectMapper mapper = new ObjectMapper();
     HashMap<Object, Object> params = new HashMap<Object,Object>();
     params = mapper.readValue(json, new TypeReference<Map<String,Object>>() { });
 

     return "";
}

Client Side

jQuery(document).ready(function(){

var datas =  {id:"id",password:"password"};

jQuery.ajax({
       type: "POST",
       url: 'http://localhost:8080/url',
       data: JSON.stringify(datas),
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (result){
        if (result.status != 0){
            return;
        }
       },
       error: function (){
        alert ("Error");
       }
});
});

Result : java.io.EOFException: No content to map to Object due to end of input
symptom : method=RequestMethod.GET change to POST

2012년 11월 26일 월요일

spring security grantedauthorityimpl deprecated

Spring Security  grantedauthorityimpl deprecated

grantedauthorityimpl  to SimpleGrantedAuthority



       userAuthorities.add (new SimpleGrantedAuthority(String role));



Example 


  Vector<GrantedAuthority> userAuthorities = new Vector<GrantedAuthority>();
          
  List<UserRole> userRole = userService.getUserRole(params);
      
  ListIterator<UserRole> userRoleLiterator =  userRole.listIterator();
          
  while (userRoleLiterator.hasNext()){
         String tempRole = userRoleLiterator.next().getAuthority();
         userAuthorities.add(new  SimpleGrantedAuthority (tempRole));
  }



  위와 같이 GrantedAuthorityImpl 대신 SimpleGrantedAuthority 를 사용하면 된다

2012년 11월 21일 수요일

addressDao

package com.examples.dao;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.examples.vo.AddressVO;
@CacheNamespace(implementation=org.mybatis.caches.ehcache.EhcacheCache.class)
Public interface AddressDAO{
 String GET_ADDRESS_BY_ID = "SELECT * FROM vw_address WHERE id = #{addressId}";
 String INSERT_ADDRESS  = "INSERT into address (building,street,location,town,postCode,countyId,countryId,notes,createdOn,createdBy,active)
               VALUES (#{building},#{street},#{location},#{town},#{postCode},#{countyId},#{countryId},#{notes},sysdate(),#{createdBy},1)";
 String UPDATE_ADDRESS    = "UPDATE address set building=#{building},countyId=#{countyId}, street=#{street},location=#{location},town=#{town},postCode=#{postCode},notes=#{notes},modifiedOn=sysdate(),modifiedBy=#{modifiedBy},countryId=#{countryId} where id= #{id}";
 String DELETE_ADDRESS    = "DELETE from address WHERE id = #{addressId}";

        @Select(GET_ADDRESS_BY_ID)
        @Options(useCache=true)
        public AddressVO doSelectAddress(long addressId) throws Exception; 
        @Insert(INSERT_ADDRESS)
 @Options(useGeneratedKeys = true, keyProperty = "id", flushCache=true)
 public int doCreateAddress(AddressVO address) throws Exception;
 @Update(UPDATE_ADDRESS)
 @Options(flushCache=true)
 public int doUpdateAddress(AddressVO address) throws Exception;
 @Delete(DELETE_ADDRESS)
 @Options(flushCache=true)
 public int doDeleteAddress(long addressId) throws Exception;
}

package com.examples.dao;
import java.util.List;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.examples.vo.AddressVO;
import com.examples.vo.CandidateVO;
import com.examples.vo.EmployerVO;
import com.examples.vo.PersonVO;
@CacheNamespace(implementation=org.mybatis.caches.ehcache.EhcacheCache.class)
public interface CandidateDAO {
 String GET_CANDIDATE_BY_ID="select c.* from candidate c where id=#{id} and active=1"; 
 String GET_CANDIDATES_BY_USER_COMPANY = "select * from vw_company_candidate where companyId=#{companyId} and active=1";
 String GET_CANDIDATE_BY_ID_AND_USER_COMPANY = "select * from vw_company_candidate where companyId=#{companyId} and id=#{candidateId} and active=1";
 String INSERT_CANDIDATE = "INSERT INTO candidate (" +
   " personId,addressId,employerId,clientId,basic,ote,met," +
   " reference,exclusive,createdOn,createdBy,active," +
   " priority,code,offers,referredBy,statusId,salCurrencyId,salTenureId) " +
    "VALUES " +
      " (#{person.id},#{address.id},#{employer.id},#{client.id}," +
      " #{basic},#{ote},#{met},#{reference}," +
      " #{exclusive},sysdate(),#{createdBy},1,#{priority}," +
      " #{code},#{offers},#{referredBy},#{statusId},#{salCurrencyId},#{salTenureId})";
 String UPDATE_CANDIDATE = "UPDATE candidate SET " +
      " personId=#{person.id}, addressId=#{address.id}, employerId=#{employer.id}, clientId=#{client.id}," +
      " basic=#{basic}, ote=#{ote},met=#{met},reference=#{reference}," +
      " exclusive=#{exclusive},modifiedOn=sysdate(),modifiedBy=#{modifiedBy},active=#{active},priority=#{priority}," +
      " code=#{code},offers=#{offers},referredBy=#{referredBy},statusId=#{statusId}, " +
      " salCurrencyId=#{salCurrencyId},salTenureId=#{salTenureId} where id=#{id}";
 String DELETE_CANDIDATE = "update candidate set active=0 where id=#{candidateId}";
 String MAP_CANDIDATE_SECTOR = "insert ignore into candidate_sector(sectorId,candidateId) values (#{sectorId},#{candidateId})";
 @Select(GET_CANDIDATES_BY_USER_COMPANY)
 @Results(value = {
  @Result(property="id", column="id"),
  @Result(property="person",  column="personId",  javaType=PersonVO.class, mailto:one=@One(select=%22com.examples.dao.PersonDAO.doSelectPerson")),
  @Result(property="address", column="addressId", javaType=AddressVO.class, mailto:one=@One(select=%22com.examples.dao.AddressDAO.doSelectAddress"))
 })
 public List<candidatevo> doSelectCandidatesByCompany(long companyId);
 @Select(GET_CANDIDATE_BY_ID)
 @Results({
    @Result(property="id",     column="id"),
    @Result(property="person", column="personId",   javaType=PersonVO.class, mailto:one=@One(select=%22com.examples.dao.PersonDAO.doSelectPerson")),
    @Result(property="address",column="addressId",  javaType=AddressVO.class, mailto:one=@One(select=%22com.examples.dao.AddressDAO.doSelectAddress")),
                         @Result(property="sectors", column="id",   javaType=List.class,many=@Many(select = "com.examples.dao.SectorDAO.doSelectSectorsByCandidate"))
    })

        public CandidateVO doSelectCandidateById(long candidateId);
 @Insert(INSERT_CANDIDATE)
 @Options(useGeneratedKeys = true, keyProperty = "id", flushCache=true)
 public int doCreateCandidate(CandidateVO candidate) throws Exception;

        @Update(UPDATE_CANDIDATE)
 @Options(flushCache=true)
 public int doUpdateCandidate(CandidateVO candidate) throws Exception;
 @Delete(DELETE_CANDIDATE)
 @Options(flushCache=true)
 public int doDeleteCandidate(long candidateId) throws Exception;

        @Insert(MAP_CANDIDATE_SECTOR)
 public void doMapCandidateSector(@Param("sectorId") long sectorId, @Param("candidateId") long candidateId);
}
</candidatevo>

mybatis



    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
       <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
       <property name="url" value="jdbc:oracle:thin:@:1521:" />
       <property name="username" value="" />
       <property name="password" value="" />
    </bean>

    <bean id="transactionManager"    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource" />
       </bean>
   
   
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref="dataSource" />
          <property name="configLocaltion" value="/WEB-INF/spring/mybatis.xml"></property>
          <property name="mapperLocations" value="com/sbs/news/article/mapper/*.xml" />
       </bean>

<configuration>
 <typeAliases>
  <typeAlias type="com.sbs.news.model.Article" alias="Article"/>
 </typeAliases>

    <mappers>
        <mapper resource="maps/UserDao.xml" />
    </mappers>
</configuration>

spring security 사용상 주의점

Spring3에서 Security 사용

다음과 같을때 유용하다.
1. 관리자에게 권할 별로 접근 메뉴가 다르다(일반운영자, 최종관리자)
2. 동시접속로그인을 제한한다.

url별로 접근 제한을 할 수 있고 권한에 대해 인증을 할 수 있고 로그아웃, 로그인, 세션생성, 비밀번호체크등 많은 클래스파일 작업이 필요없다.


참조 : http://static.springsource.org/spring-security/site/docs/3.0.x/reference/springsecurity-single.html

1. web.xml 편집

1.1 contextConfigLocation 에 security.xml을 추가한다.
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            classpath:security-context.xml
        </param-value>
    </context-param>


* 여기서 주의할 점은 servlet에서 적용한 contextConfigLocation에 사용하지 말아야 한다. 
이부분에 대해서는 http://actionscripter.tistory.com/28 를 참조 바란다.

    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:web-context.xml
                classpath:security-context.xml<!-- 이곳에 이렇게 넣지 마세요 -->
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>




1.2  springSecurityFilterChain 의 filter와 filter-mapping 을추가 

<filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

이로서 web.xml 수정되었다. 
이렇게 적용한후 실행을 하게되면 
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined 부분의 에러가 발생한다.

springSecurityFilterChain 을 정의해 주어야 한다는 내용인데 web.xml의 contextConfigLocation 에서 정의된 security-context.xml 파일을 수정하자


2. applicationContext-security.xml 편집
2.1 http 설정

<http auto-config='true'>
    <intercept-url pattern="/**" access="ROLE_USER" />
</http>

그릭 다시 실행을 하면  No bean named 'org.springframework.security.authenticationManager' is defined 이 발생한다.

2.2
<authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
        <user name="bob" password="bobspassword" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager>

을 함께 넣어주면 실제적으로 로그인 페이지가 뜨는 것을 확인할 수 있다.
이때 로그인을 하기위해서는 authentication-provider 에서 정의된 user name 과 password 를 넣어주면 된다.



[security-context.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- ***************************************************************************** -->
    <!-- This context file exists for developers to enter in their own security configurations. -->
    <!-- ***************************************************************************** -->
    <http auto-config='true'>
        <intercept-url pattern="/**" access="ROLE_USER" />
    </http>
    
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
                <user name="bob" password="bobspassword" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

security xml sample

<?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.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    <debug/>      
    
 
          
    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <beans:property name="driverClassName" value="oracle.jdbc.OracleDriver" ></beans:property>
    <beans:property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" ></beans:property>
    <beans:property name="username" value="spring" ></beans:property>
    <beans:property name="password" value="cs550" ></beans:property>
 </beans:bean>
    <http pattern="/images/**"    security="none"/>
    <http pattern="/ckeditor/**"  security="none"/>
    <http pattern="/jquery/**"    security="none"/>
    <http pattern="/grid/**"      security="none"/>
 <http pattern="/css/**"       security="none"/>
 <http pattern="/resources/**" security="none"/>

 <http auto-config="true" use-expressions="true" >
    
        <intercept-url pattern="/login"  access="permitAll"/>
  <intercept-url pattern="/logout" access="permitAll"/>
  <intercept-url pattern="/denied" access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/**"     access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/user"   access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/admin"  access="hasRole('ROLE_ADMIN')"/>

  <form-login login-page="/login"
   authentication-failure-url="/login/failure"
   default-target-url="/"/>

  <access-denied-handler error-page="/denied"/>

  <logout invalidate-session="true"
   logout-success-url="/logout/success"
   logout-url="/logout"/>
      
    </http>
    <authentication-manager>
       <authentication-provider>
          <jdbc-user-service data-source-ref="dataSource"
               users-by-username-query="select username,password, enabled from users where username=?"
         authorities-by-username-query="select u.username, ur.authority from users u,authorities ur
              where u.username = ur.username and u.username =?"
          />
       </authentication-provider>
    </authentication-manager>     
  
</beans:beans>

2012년 4월 30일 월요일

ibatis procedure call

<parameterMap id="myParamMap" class="java.util.Map"> 
<parameter property="username" mode="IN" /> 
<parameter property="roles1" jdbcType="ORACLECURSOR" mode="OUT" /> 
<parameter property="roles2" jdbcType="ORACLECURSOR" mode="OUT" /> 
<parameter property="roles3" jdbcType="ORACLECURSOR" mode="OUT" /> 

</parameterMap