Spring Boot + Freemarker 多語言國際化的作法

1. 在 application.properties 增加

# ===============================
# Multi Language
# ===============================
spring.messages.basename=i18n/messages

# 為了取得當前頁面的URL (get current page url)
spring.freemarker.expose-spring-macro-helpers=true

2. 在 resource 目錄下建立一個目錄 i18n , 並新增三個檔

messages.properties , messages_zh_TW.properties , 內容為

label.login =  登入

messages_en_US.properties 內容為

label.login =  Login

3. 建立 WebMvcConfig : MvcConfig.class

@Configuration
public class MvcConfig implements WebMvcConfigurer {    
    //多語系設定
    @Bean(name = "localeResolver")
    public LocaleResolver getLocaleResolver()  {
        CookieLocaleResolver resolver= new CookieLocaleResolver();
        resolver.setCookieDomain("jwtLocaleCookie");
        // 60 minutes 
        resolver.setCookieMaxAge(60*60); 
        return resolver;
    } 
    //多語系設定 語系切換偵測
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
        localeInterceptor.setParamName("lang");
                  
        registry.addInterceptor(localeInterceptor).addPathPatterns("/*");
    }

}

4. Control file: MainController.class

@Controller
public class MainController {
        
        @RequestMapping(value = { "/","/home" })
    public String staticResource(Model model) {
        return "home";
    }

}

5. View: home.ftl

<#import "/spring.ftl" as spring/>





注意, FTL的第一行要 import "/spring.ftl" ,這樣子就可以輕鬆切換語系了

 

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

使用 Hibernate Tool 產生 Model 時, FetchType 預設是 FetchType.LAZY , 但在執行時, 卻常會產生類似下列 no Session 的錯誤訊息

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.spring.jwt.db.maria.model.authentication.User.userAuthorities, could not initialize proxy - no Session

 

這時候需要在 Method 前加入 @Transactional 就可以解決

@Test
@Transactional
public void testUserAuthority() {
        User user = userRepository.findById(1L).get();
        JwtUser jwtUser = JwtUserFactory.create(user);
        logger.info(jwtUser.getUsername());
        
}

Ref: http://javasampleapproach.com/hibernate/use-hibernate-lazy-fetch-eager-fetch-type-spring-boot-mysql

MIS 發表在 痞客邦 留言(0) 人氣()

使用 Spring Boot 2 建置系統就是希望快速. 若專案範圍小的話, 資料庫倒是可以考慮使用 H2 database 來建罝

在 build.gradle 上加入

compile('com.h2database:h2')

然後編輯 application.properties

server.port=8088
# ===============================
# H2
# ===============================
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

這樣就可以登入 http://localhost:8088/h2-console 操作了

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

 環境: ApacheFriends XAMPP Version 7.1.7

  + Apache 2.4.26
  + MariaDB 10.1.25
  + PHP 7.1.7 (VC14 X86 32bit thread safe) + PEAR
  + phpMyAdmin 4.7.0
  + OpenSSL 1.0.2f
  + ADOdb 518a
  + Mercury Mail Transport System v4.63 (not included in the portable version)
  + FileZilla FTP Server 0.9.41 (not included in the portable version)
  + Webalizer 2.23-04 (not included in the portable version)
  + Strawberry Perl 5.16.1.1 Portable
  + Tomcat 7.0.56
  + XAMPP Control Panel Version 3.2.2 by hackattack142

Step01: 先將 php.ini 裡的 extension=php_pdo_oci.dll 注釋移除

; Be sure to appropriately set the extension_dir directive.
;
extension=php_bz2.dll
extension=php_curl.dll
extension=php_fileinfo.dll
;extension=php_ftp.dll
extension=php_gd2.dll
extension=php_gettext.dll
;extension=php_gmp.dll
;extension=php_intl.dll
;extension=php_imap.dll
;extension=php_interbase.dll
;extension=php_ldap.dll
extension=php_mbstring.dll
extension=php_exif.dll      ; Must be after mbstring as it depends on it
extension=php_mysqli.dll
;extension=php_oci8_12c.dll  ; Use with Oracle Database 12c Instant Client
;extension=php_openssl.dll
;extension=php_pdo_firebird.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
;extension=php_pdo_odbc.dll
;extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
;extension=php_pgsql.dll
;extension=php_shmop.dll

Step02: 在 common\config 裡增加兩個檔 dbMaria.php & dbOracle.php

dbMaria.php

<?php
return [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=mysite', // MySQL, MariaDB
        //'dsn' => 'sqlite:/path/to/database/file', // SQLite
        //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL
        //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID
        //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver
        //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver
        //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver
        //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle
        'username' => 'root',
        'password' => 'password',
        'charset' => 'utf8',
];
?>   

dbOracle.php

<?php
return [
        'class' => 'yii\db\Connection',
        //'dsn' => 'mysql:host=localhost;dbname=mysite', // MySQL, MariaDB
        //'dsn' => 'sqlite:/path/to/database/file', // SQLite
        //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL
        //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID
        //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver
        //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver
        //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver
        'dsn' => 'oci:dbname=//localhost:1521/xe;charset=AL32UTF8', // Oracle  ;charset=AL32UTF8=>解決中文亂碼
        'username' => 'system',
        'password' => 'password',
];
?>   

Step03 : 修改 common\config 裡的 main-local.php

<?php
return [
    'components' => [
        'db'=>require(__DIR__ . '/dbMaria.php'),
        'db2'=>require(__DIR__ . '/dbOracle.php'),

        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
    ],
    'timeZone' => 'Asia/Taipei',
];

Step04: 測試:

   /**
     * Displays a single Post model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
//         $post = Yii::$app->db->createCommand('select * from post
//                     where id=:id and status=:status')
//                     ->bindValue(':id', $_GET['id'])
//                     ->bindValue(':status', 2)
//                     ->queryOne();

//         $post = Post::find()->where(['id'=>$id])->one();
//         $post = Post::findOne(['id'=>$id]);
//         var_dump($post);
//         $posts = Post::findAll(['status'=>2]);
//         $posts = Post::find()->where(['and','author_id=1', ['status'=>2],['like','title','yii2']])
//                              ->orderBy('id')->all();        
//         var_dump($posts);

        $users = Yii::$app->db2->createCommand('select * from spfs.USER_DETAILS')->queryAll();        
        var_dump($users);
        exit(0);

        
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

 

 

 

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

在 Tomcat 的 server.xml 裡設定

<Context docBase="weixin" path="/weixin" reloadable="true" source="org.eclipse.jst.jee.server:weixin">
        <Resource name="jdbc/mysqlLocalDS01" username="root" password="password" url="jdbc:mysql://localhost:3306?characterEncoding=utf-8" auth="Container" driverClassName="com.mysql.cj.jdbc.Driver" factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory" maxIdle="10" maxTotal="20" maxWaitMillis="-1" type="javax.sql.DataSource" />      
        <Resource name="jdbc/JappsDS01" username="ap" password="password" url="jdbc:oracle:thin:@127.0.0.1:1521:xe" driverClassName="oracle.jdbc.driver.OracleDriver" maxIdle="2" maxTotal="4" maxWaitMillis="5000"  type="javax.sql.DataSource" validationQuery="select 1 from dual"/>
    <Resources>
       <PreResources base="C://CKFinderJava//userfiles" className="org.apache.catalina.webresources.DirResourceSet" webAppMount="/userfiles"/>
   </Resources>
</Context>

在 JBoss EAP 6.x 上, 需建一個檔案: WEB-INF\jboss-web.xml

<jboss-web version="7.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jboss="http://www.jboss.com/xml/ns/javaee"  
               xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee jboss-web_7_0.xsd">  
        <symbolic-linking-enabled>true</symbolic-linking-enabled>    
        <overlay>C:/CKFinderJava/userfiles</overlay>
 
</jboss-web>

就可以用下列的連結來看檔案。

PS: mis 是目前的專案,而 images/S_13164601.jpgC:/CKFinderJava/userfiles 下的目錄及檔案

http://localhost:8080/mis/images/S_13164601.jpg

 

REF: https://developer.jboss.org/thread/266445

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

環境:

eclipse : https://eclipse.org/downloads/packages/release/Neon/3

python: Python 3.6.1

django: Django-1.11.1.tar.gz

先下載 Python 3.6.1 安裝在 C:\Python\Python36-32 然後增加 Path

Django-1.11.1.tar.gz 解壓縮在 C:\Python\Python36-32 目錄下,然後執行下列指令

C:\Python\Python36-32\Django-1.11.1\python setup.py install

 

最後在eclipse 的 Preferences 設定即可

參考:

http://www.pydev.org/download.html

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

用 Hibernet Tool 自動產生的 Domain Code,對於 FOREIGN KEY 會以 annotation:  @ManyToMany(fetch = FetchType.LAZY) 來作註,但執行時會發生下列的錯誤

Struts Problem Report

Struts has detected an unhandled exception:

Messages:
  • failed to lazily initialize a collection of role: com.mis.model.Admin.roles, could not initialize proxy - no Session
File: org/hibernate/collection/internal/AbstractPersistentCollection.java
 

Stacktraces

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.mis.model.Admin.roles, could not initialize proxy - no Session

 

解決方法: 由 FetchType.LAZY 改成 FetchType.EAGER

    //@ManyToMany(fetch = FetchType.LAZY)
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "admin_roles", catalog = "weixin", joinColumns = {
            @JoinColumn(name = "aid", nullable = false, updatable = false) }, inverseJoinColumns = {
                    @JoinColumn(name = "rid", nullable = false, updatable = false) })
    public Set<Role> getRoles() {
        return this.roles;
    }

 

或者是在 applicationContext.xml 加入 <prop key="hibernate.enable_lazy_load_no_trans">true</prop> 如下

    <!-- Configure the entity manager factory bean : Step02-Start-->    
    <bean id="emfLocalDS"    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">        
        <property name="dataSource" ref="LocalDS"></property>         
        <property name="persistenceUnitName" value="emfLocalPU"/>
        <!-- Set base package of your entities -->
        <property name="packagesToScan" value="com.mis.model"/>
        <!-- Set share cache mode -->
        <property name="sharedCacheMode" value="ENABLE_SELECTIVE"/>
        <!-- Set validation mode -->
        <property name="validationMode" value="NONE"/>         
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="MYSQL" />
                <property name="showSql" value="true" />
            </bean>
        </property>

        <!-- Set JPA properties -->
        <property name="jpaProperties">
            <props>
                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                 <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
            </props>
        </property>       
    </bean>
    <!-- Configure the entity manager factory bean : Step02-End-->

參考:

http://stackoverflow.com/questions/11746499/solve-failed-to-lazily-initialize-a-collection-of-role-exception

http://www.lostinsoftware.com/2015/08/reverse-engineering-and-code-generation/

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

作法如下:

http://stackoverflow.com/questions/26616723/java-lang-nosuchmethoderror-javax-persistence-table-indexesljavax-persistenc

If you are using Jboss 7.1.1, jboss already has hibernate-jpa-2.0 in its classpath, so during runtime it uses the one in its classpath, not the one you've deployed with your app , to point jboss to the hibernate-jpa-2.1 do the following:

  1. copy hibernate-jpa-2.1-api-1.0.0.final.jar to the following directory : jboss-as-7.1.1.Final/modules/javax/persistence/api/main

  2. open module.xml and change the resource-root as follows : resource-root path="hibernate-jpa-2.1-api-1.0.0.final.jar" (pointing it to jpa 2.1)

  3. re-compile and re-deploy your app, then you are good to go.

module.xml 檔案內容, 置換成 hibernate-jpa-2.1-api-1.0.0.Final.jar :

<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ JBoss, Home of Professional Open Source.
  ~ Copyright 2010, Red Hat, Inc., and individual contributors
  ~ as indicated by the @author tags. See the copyright.txt file in the
  ~ distribution for a full listing of individual contributors.
  ~
  ~ This is free software; you can redistribute it and/or modify it
  ~ under the terms of the GNU Lesser General Public License as
  ~ published by the Free Software Foundation; either version 2.1 of
  ~ the License, or (at your option) any later version.
  ~
  ~ This software is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
  ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  ~ Lesser General Public License for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public
  ~ License along with this software; if not, write to the Free
  ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  -->

<module xmlns="urn:jboss:module:1.1" name="javax.persistence.api">
    <dependencies>
        <!-- PersistenceUnitInfo needs javax.sql.DataSource -->
        <module name="javax.api" export="true"/>
    </dependencies>

    <resources>
        <resource-root path="hibernate-jpa-2.1-api-1.0.0.Final.jar"/>
        <!-- Insert resources here -->
    </resources>
</module>

 

文章標籤

MIS 發表在 痞客邦 留言(0) 人氣()

所需軟體

1. OS: windows 7

2. xampp-portable-win32-5.5.38-3-VC11.zip

3. FreeRADIUS.net-1.1.7-r0.0.2.exe - 6.74 MB - Licence: GNU/LGPL

4. NTRadPing 測試工具

安裝:

Step 1: 主機端(192.168.1.1):安裝 FreeRADIUS.net-1.1.7-r0.0.2.exe 完後,執行 C:\FreeRADIUS.net\bin\radtest.bat,應該本機測試會正常

Step 2: 修改 C:\FreeRADIUS.net\etc\raddb\clients.conf

## 增加 client 電腦端 test
client 192.168.1.4 {
    secret        = testing123
    shortname    = private-network-3
}

Step 3: 修改 C:\FreeRADIUS.net\etc\raddb\users.conf

## 增加一筆測試帳號

polinwei    User-Password == "password"

Step 4: 用 NTRadPing  測試,填入資訊如下。應該可以測試正常

 

整合 MySQL

Step1: 用 XAMPP 建立 MySQL DB: "radius",並匯入 C:\FreeRADIUS.net\share\doc\freeradius\examples\mysql.sql

Step2: 建立測試資料

INSERT INTO `radgroupreply` (`id`, `GroupName`, `Attribute`, `op`, `Value`) VALUES
(1, 'user', 'Auth-Type', ':=', 'Local'),
(2, 'user', 'Service-Type', ':=', 'Framed-User'),
(3, 'user', 'Framed-IP-Address', ':=', '255.255.255.254'),
(4, 'user', 'Framed-IP-Netmask', ':=', '255.255.255.0');


INSERT INTO `radcheck` (`id`, `UserName`, `Attribute`, `op`, `Value`) VALUES
(1, 'sqltest', 'User-Password', ':=', 'testpwd'),
(2, 'polinwei', 'User-Password', ':=', '12345');

Step3: 修改 radius.conf

#第1784行
authorize {
    #
    #  Read the 'users' file
#    files

    #
    #  Look in an SQL database.  The schema of the database
    #  is meant to mirror the "users" file.
    #
    #  See "Authorization Queries" in sql.conf
    sql

#第1989行
accounting {
    #
    #  Log traffic to an SQL database.
    #
    #  See "Accounting queries" in sql.conf
    sql

Step4: 修改 radius.conf,注意:windows 7 因為有 ipv6 ,所以用 127.0.0.1 代替 localhost 。這樣 FreeRADIUS 連結 mysql 才不會有問題。

sql {
    # Database type
    # Current supported are: rlm_sql_mysql, rlm_sql_postgresql,
    # rlm_sql_iodbc, rlm_sql_oracle, rlm_sql_unixodbc, rlm_sql_freetds
    driver = "rlm_sql_mysql"

    # Connect info
    server = "127.0.0.1"
    login = "radius"
    password = "password"

    # Database table configuration
    radius_db = "radius"

這樣就大工告成了。

 

 

 

 

文章標籤

MIS 發表在 痞客邦 留言(1) 人氣()

在目錄 %JBOSS_HOME%\modules\com\microsoft\sqlserver\jdbc\main 下放入 module.xml & sqljdbc42.jar

module.xml 的內容

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.microsoft.sqlserver.jdbc">
 <resources>
  <resource-root path="sqljdbc42.jar"/>
 </resources>
 <dependencies>
  <module name="javax.api"/>
  <module name="javax.xml.bind.api"/>
  <module name="javax.transaction.api"/>
 </dependencies>
</module>

編輯 %JBOSS_HOME%\standalone\configuration\standalone.xml

<datasource jndi-name="java:/mssqlDS" pool-name="LansweeperDS" enabled="true">
    <connection-url>jdbc:sqlserver://mssql_IP\SQLEXPRESS;DatabaseName=mydb</connection-url>
    <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
    <driver>sqlserver</driver>
    <security>
        <user-name>sa</user-name>
        <password>password</password>
    </security>
    <validation>
        <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mssql.MSSQLValidConnectionChecker"/>
    </validation>
</datasource>

<driver name="sqlserver" module="com.microsoft.sqlserver.jdbc">
    <xa-datasource-class>com.microsoft.sqlserver.jdbc.SQLServerXADataSource</xa-datasource-class>
</driver>

這樣就可以了

MIS 發表在 痞客邦 留言(0) 人氣()