View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.samples.sprhib.dao;
20  
21  import org.apache.shiro.crypto.hash.Sha256Hash;
22  import org.hibernate.SessionFactory;
23  import org.springframework.beans.factory.InitializingBean;
24  import org.springframework.beans.factory.annotation.Autowired;
25  import org.springframework.jdbc.core.JdbcTemplate;
26  import org.springframework.stereotype.Component;
27  
28  import javax.sql.DataSource;
29  
30  /**
31   * Loads sample data for the sample app since it's an in-memory database.
32   */
33  @Component
34  public class BootstrapDataPopulator implements InitializingBean {
35  
36      private DataSource dataSource;
37      @SuppressWarnings({"FieldCanBeLocal"})
38      private SessionFactory sessionFactory;
39  
40      @Autowired
41      public void setDataSource(DataSource dataSource) {
42          this.dataSource = dataSource;
43      }
44  
45      // Session factory is only injected to ensure it is initialized before this runs
46      @Autowired
47      public void setSessionFactory(SessionFactory sessionFactory) {
48          this.sessionFactory = sessionFactory;
49      }
50  
51      public void afterPropertiesSet() throws Exception {
52          //because we're using an in-memory hsqldb for the sample app, a new one will be created each time the
53          //app starts, so insert the sample admin user at startup:
54          JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
55  
56          jdbcTemplate.execute("insert into roles values (1, 'user', 'The default role given to all users.')");
57          jdbcTemplate.execute("insert into roles values (2, 'admin', 'The administrator role only given to site admins')");
58          jdbcTemplate.execute("insert into roles_permissions values (2, 'user:*')");
59          jdbcTemplate.execute("insert into users(id,username,email,password) values (1, 'admin', 'sample@shiro.apache.org', '" + new Sha256Hash("admin").toHex() + "')");
60          jdbcTemplate.execute("insert into users_roles values (1, 2)");
61  
62  
63      }
64  }