星期四, 2月 09, 2012

[Java] Insert if not exist: 資料列不存在時才新增


重覆的連絡人清單就不要插入!!
重點在select * from (select 2,'ken') as tmpInsert記得要重新給一個別名,
不然編譯都會爆炸給你看lol

範例:
插入一個使用者ken到聯絡人清單索引為2的結果

insert into contact_list_member(contact_list_id,uid)
select * from (select 2,'ken') as tmpInsert
where not exists(select 1 from contact_list_member clm where clm .contact_list_id= 2 and  clm .uid='ken')


使用preparedstatement就會像下面那樣
//insert if not exist
   String insertMemberSql= 
    "insert into contact_list_member(contact_list_id,uid) select * from (select ?,?) as tmpInsert where not exists(select * from contact_list_member where contact_list_id=? and uid=?)";

Update 2012/03/08 今天在同事的測試下發現上面的語句在插入的值都一樣的時候所產生的duplicate column name bug,簡單的用新增使用者的範例來記綠一下 

範例:
以下語句要新增一個帳號跟密碼都是叫cindy,不一樣就不會有這個問題!!

insert into users(account,password) select* from (select 'cindy','cindy') as tmpInsert where not exists(select 1 from users where account = 'cindy')

 問題: 錯誤的原因在於我們要建立一個帳號跟密碼一樣的使用者,會造成表格出現重覆欄位名稱的問題(Duplicate column name 'cindy'錯誤)

 以下是產生這個錯誤的SQL片段

select* from (select 'cindy','cindy') as tmpInsert 解法

因tmpInsert已經含有重覆的column name了,因此我們需要指定tmpInsert內的column name,才不會讓表格內的欄位名稱重覆的異常

 select account ,password from (select 'cindy' as account ,'cindy' as password) as tmpInsert

上述語句會產生的tmpInsert資料表結果集

account  |  password
cindy     |  cindy

Reference: MySQL一個聰明的sql,當Record沒有的時候才增加
不存在时才插入数据

星期二, 2月 07, 2012

[Java] JDBC ResultSet/RowSet 取得查詢結果的總列數

常常需要得到查詢結果返回的總列數,
Java提供以下三種解法:

[Java] 必學!! 取得當前新增資料的索引值

當在MySQL使用AUTO_INCREMENT產生索引的值,如何取得新增的索引值呢?

MySQL提供了LAST_INSERT_ID()解決這個問題!!

SELECT LAST_INSERT_ID();


如果要用JDBC實作的話只需要加入Statement.RETURN_GENERATED_KEYS,
執行getGeneratedKeys()即可輕鬆取得!!

星期一, 2月 06, 2012

[Alfresco] Boolean type is in FTL

在ftl檔案遇到boolean欄位一開始所遇到的錯誤

{
"shareDpxStatus": <#if person.properties.shareDpxStatus??>${person.properties.shareDpxStatus}<#else>null
}


原來ftl檔不支援直接將boolean型態印出來,要先轉換成字串型態
解法如下:
{
"shareDpxStatus": <#if person.properties.shareDpxStatus??>${person.properties.shareDpxStatus?string("true","false")}<#else>null
}

星期日, 2月 05, 2012

[Java] JDBC Transaction

本篇說明如何在JDBC實作Transaction機制。

步驟一:MsSQL設定:
設定INNODB資料表

Tip:MySQL 對不同的 Table 可以選擇不同的 Implementation 方式,像是最早的 ISAM (ISAM 將在 MySQL 5.0 以後被移除),後來的 MyISAM (因為要做 Transaction 時要預留多一點空間來進行處理,因此如果不須使用 Transaction 時,直接建 Table 就會採用 MyISAM 的格式)、把 Table 存在記憶體中提升效能的 HEAP Table,以及有支援 Transaction 的 INNODB 格式。
步驟二:如何在Java code執行Transcation

星期二, 1月 31, 2012

星期一, 1月 30, 2012

[Alfresco] Pagination of Lucene

使用javascript API的search.query(searchParameters)方法時,
當skipCount超過一千筆時,會無法取得回傳的結果,
導致客製化分頁會失敗。

找到以下這篇跟我遇到一樣的問題:
Improve the skipCount function not to check the permissions.

記錄一下:
This is an enhancement request for paging offset in FTS query called "skipcount". Alfresco don't have to check permission of skipped items when we specify the skipCount. 

(*1 system.max.permissionChecks 1000 as the default) 

I know the paging search itself won't be affected by the permission check as far as I tested it with an out of box webscripts named "children.get. js". So, in this case it works very fine, because this webscript uses "group.getChildGroups(maxItems, skipCount)" with ModelUtil.paging internally, so with this webscripts I can correctly get the result more than the specified number to the permission check. I attached the webscript, please find the sample-webscripts.zip for your reference. 


But, the problem is that if we use the paging offset in FTS query called "skipcount" combined with the Lucene search query in the WebScripts as follows, then it will be affected by the permission check. I attached the webscirpts named paging-result.zip for your reference. 

    var skipCount = 0 + args["skip"]; 
    var searchParams = {}; 
    searchParams.query = "cm\:name:document*"; 
    searchParams.language = "fts-alfresco"; 
    var paging = {}; 
    paging.maxItems = 100; 
    paging.skipCount = skipCount; 
    paging.totalItems = 100, 
    searchParams.page = paging; 
    var results = search.query(searchParams); 
    model["length"] = results.length; 
    model["results"] = results; 

In this case, when we specify the skipcount below the number of system.max.permissionCheck for example 1000 as the default, and set a proper paging value, then it will return the correct result, but the problem is when we specify skipcount over 1,000, then webscripts returns no results (zero items). 
So, the work around is to set over 1,000 to the "system.acl.maxPermissionChecks" , then we can get the results correctly. But increasing this parameter will give more stress to Alfresco server, so that would be nice if we could improve the function of skipCount since Alfresco don't have to check the permission of skipped items when we specify the skipCount. 


請在repository.properties修正以下二個參數
#
# Properties to limit resources spent on individual searches
#
# The maximum time spent pruning results
system.acl.maxPermissionCheckTimeMillis=100000
# The maximum number of results to perform permission checks against
system.acl.maxPermissionChecks=10000

不過當存取超過10000的時候發生以下例外錯誤!!(待續)
目前限制只能取到一層的一萬筆,當該層超過一萬筆後就拿不到資料!!
Transactional update cache 'org.alfresco.cache.node.aspectsTransactionalCache' is full (10000)

星期四, 1月 12, 2012

[Java] 自訂Exception

簡單的自訂例外處理
public class HttpClientException extends Exception{
 
 private String protocol = null;
 private String endpoint = null;
 private String httpMethod = null;
 private String postParameters = null;
 private int statuscode = 0;
 private String msg = null;
 
 public HttpClientException(String msg){
  super(msg);
 }
 
 public HttpClientException(String endpoint,String httpMethod,String postParameters,int statuscode,String msg){
  this.endpoint = endpoint;
  //detect protocal from endpoint
  if(this.endpoint.contains("https"))
   this.protocol = "HTTPS";
  else
   this.protocol = "HTTP";
  
  this.httpMethod = httpMethod;
  this.postParameters = postParameters;
  this.statuscode = statuscode;
  this.msg = msg;
 }
 
 public String getEndPoint(){
  return this.protocol + " Request Endpoint:" + this.endpoint;
 }
 
 public String getHttpMethod(){
  return this.protocol +  " Request Method:" + this.httpMethod;
 }
 
 public String getRequestBody(){
  if(this.postParameters != null)
   return this.protocol + " Request Body:" + this.postParameters;
  else
   return "Can't get request body.";
 }
 
 public String getStatusCode(){
  return this.protocol + " Status Code:" + this.statuscode;
 }
 
 public String getErrorMessage(){
  return this.protocol + " Error Message:" + this.msg;
 }
}

星期三, 1月 11, 2012

[Java] 字串比對搜尋

Java字串搜尋的方法:

  String endpoint = "http://www.google.com.tw";
  System.out.println("string index of http:" + endpoint.indexOf("http://"));
  
  endpoint = "https://www.google.com.tw";
  System.out.println("string index of https:" + endpoint.indexOf("https://"));
  
  System.out.println("string re:" + endpoint.matches("^https://.*"));
  System.out.println("string contain:" + endpoint.contains("http"));

星期一, 1月 09, 2012

[Alfresco] Dot symbol in account

先前寫了一個範例關於在URL上面有uid含有dot符號會發生問題!!
原本以為是alfresco不支援,結果是自已搞錯了XD
會發生以下錯誤!!
GET http:///alfresco/service/test/person/?alf_ticket=
UserName: ken.tsai
後端顯示找不到這個uid的錯誤,因為uid被截斷了
ERROR [extensions.webscripts.AbstractRuntime] Exception from executeScript - redirecting to status template error: 00100007 Web Script format 'tsai' is not registered

參考一下原本的範例程式,發現在webscript xml的描述檔把原本的
   any
改為
   argument
就成功解決了。

後續的釐清程序之後再補

Reference:
Alfresco Web Scripts Wiki

星期一, 1月 02, 2012

console.log throws error on IE8


經測試可用的程式碼如下:
(function($){
 
 $.console = function(logger){
  if(typeof window["console"] != "undefined"){
   console.log(logger);
  }
 };
 
})(jQuery);

缺點要改用自已寫的方式,優點是在ie8有無使用開發者工具都能正常執行網頁。
Reference:
console.log throws error on Internet Explorer IE

星期二, 12月 27, 2011

[Java] Parameterized method in JDBC

JDBC supports many setXXX() methods, one for each Java data type, so that you can set parameter values directly with the desired Java data types without any conversion. Here is a list of setXXX() methods:


[Java] Preventing SQL Injection in Java

一般基礎常犯的執行sql查詢的危險寫法:

conn = pool.getConnection( );
String sql = "select * from user where username='" + username +"' and password='" + password + "'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
loggedIn = true;
 out.println("Successfully logged in");
} else {
 out.println("Username and/or password not recognized");
}


為避免執行sql語句讓hacker使用sql injection,可改用PreparedStatement物件


String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();

如何使用PreparedStatement執行批次

import java.util.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
public class MySqlPreparedStatementBatch {
  public static void main(String [] args) {
    Connection con = null;
    try {
      com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds 
        = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
      ds.setServerName("localhost");
      ds.setPortNumber(3306);
      ds.setDatabaseName("HerongDB");
      ds.setUser("Herong");
      ds.setPassword("TopSecret");
      con = ds.getConnection();

// PreparedStatement
      PreparedStatement ps = con.prepareStatement(
 "INSERT INTO Profile (FirstName, LastName) VALUES (?, ?)");

// Provide values to parameters for copy 1
      ps.setString(1,"John");
      ps.setString(2,"First");

// Create copy 1
      ps.addBatch();

// Provide values to parameters for copy 2
      ps.setString(1,"Bill");
      ps.setString(2,"Second");

// Create copy 2
      ps.addBatch();

// Provide values to parameters for copy 3
      ps.setString(1,"Mark");
      ps.setString(2,"Third");

// Create copy 3
      ps.addBatch();

// Provide values to parameters for copy 4
      ps.setString(1,"Jack");
      ps.setString(2,"Last");

// Create copy 4
      ps.addBatch();

// Execute all 4 copies
      int[] counts = ps.executeBatch();
      
      int count = 0;
      for (int i=0; i<counts.length; i++) {
       count += counts[i];
      }
      System.out.println("Total effected rows: "+count);

// Close the PreparedStatement object
      ps.close();

      con.close();        
    } catch (Exception e) {
      System.err.println("Exception: "+e.getMessage());
      e.printStackTrace();
    }
  }
}

Reference:
Preventing SQL Injection in Java PreparedStatement in Batch Mode
如何在 Java 網站應用程式中防範 SQL Injection

[Java] Regex replace matcher

專案有一個需求需要將找到的字元進行相關取代的處理,
由於每一個找到的字元需要經過decode的處理,所以不適用replaceAll方法來處理。
以下找到符合的處理方法:

Reference:http://stackoverflow.com/questions/5568081/regex-replace-all-ignore-case

Avoid ruining the original capitalization:

In the above approach however, you're ruining the capitalization of the replaced word. Here is a better suggestion:
String inText="Sony Ericsson is a leading company in mobile. " +
              "The company sony ericsson was found in oct 2001";
String word = "sony ericsson";
Pattern p = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(inText);
StringBuffer sb = new StringBuffer();
while (m.find()) {
  String replacement = m.group().replace(' ', '~');
  m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
m.appendTail(sb);
String outText = sb.toString();
System.out.println(outText);
Output:
Sony~Ericsson is a leading company in mobile.
The company sony~ericsson was found in oct 2001

其他你感興趣的文章

Related Posts with Thumbnails