星期二, 12月 27, 2011

[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

星期四, 12月 15, 2011

星期二, 12月 13, 2011

[Alfresco] Search API


Search API Example:
  var def =
  {
     query: "cm:name:test*",
     language: "fts-alfresco"
  };
  var results = search.query(def);

Parameters
search
{
   query: string,          mandatory, in appropriate format and encoded for the given language
   store: string,          optional, defaults to 'workspace://SpacesStore'
   language: string,       optional, one of: lucene, xpath, jcr-xpath, fts-alfresco - defaults to 'lucene'
   templates: [],          optional, Array of query language template objects (see below) - if supported by the language 
   sort: [],               optional, Array of sort column objects (see below) - if supported by the language
   page: object,           optional, paging information object (see below) - if supported by the language
   namespace: string,      optional, the default namespace for properties
   defaultField: string,   optional, the default field for query elements when not explicit in the query
   onerror: string         optional, result on error - one of: exception, no-results - defaults to 'exception'
}

sort
{
   column: string,         mandatory, sort column in appropriate format for the language
   ascending: boolean      optional, defaults to false
}

page
{
   maxItems: int,          optional, max number of items to return in result set
   skipCount: int          optional, number of items to skip over before returning results
}

template
{
   field: string,          mandatory, custom field name for the template
   template: string        mandatory, query template replacement for the template
}

Reference:
Full Text Search Query Syntax
Alfresco.util.DataTable and search maxItems 

What is the maximum length of a URL?

http://www.boutell.com/newfaq/misc/urllength.html

[Java] DataOutputStream 的 writeBytes(String s) 編碼問題!!

Java編碼紀綠:

java 的DataOutputStream 的 writeBytes(String s) 方法對中文編碼會錯誤


public final void writeBytes(String s) throws IOException {

int len = s.length();

for (int i = 0 ; i < len ; i++) {

out.write((byte)s.charAt(i));

}

incCount(len);

}


举个例子,以字符串"你好"作为参数输入,(byte)s.charAt(i) 这句就会导致问题,
因为java里的char类型是16位的,一个char可以存储一个中文字符,在将其转换为 byte后高8位会丢失,
这样就无法将中文字符完整的输出到输出流中。
所以在可能有中文字符输出的地方最好先将其转换为字节数组,然再通过write(byte[] b)方法输出。例:

String s = "你好";

write(s.getBytes());

注意:getBytes沒指定編碼格式的話是使用預設系統的編碼。

2012/02/09更新:
DataOutputStream模擬form post上傳的時候,改用write方法才能解決中文編碼的問題。

  /*
  --boundary\r\n
  Content-Disposition: form-data; name=""; filename=""\r\n
  Content-Type: \r\n
  \r\n
  \r\n
  */ 
  this.dataOutputStream.writeBytes(this.PREFIX);
  this.dataOutputStream.writeBytes(this.boundary);
  this.dataOutputStream.writeBytes(this.CRLF);
  this.dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"");
//  this.dataOutputStream.writeBytes(fieldName);
  this.dataOutputStream.write(fieldName.getBytes());
  this.dataOutputStream.writeBytes("\"; filename=\"");
  //don't support char in Chinese
//  this.dataOutputStream.writeBytes(fileName);
  this.dataOutputStream.write(fileName.getBytes());
  this.dataOutputStream.writeBytes("\"");
  this.dataOutputStream.writeBytes(this.CRLF);
  if(mimeType != null){
   this.dataOutputStream.writeBytes("Content-Type:");
   this.dataOutputStream.writeBytes(mimeType);
   this.dataOutputStream.writeBytes(this.CRLF);
   this.dataOutputStream.writeBytes(this.CRLF);
  }



2012/03/12 更新
今天在別的case之下竟然會讓中文亂碼,所以使用getBytes方法前還是指定你要的編碼比較合適
getBytes(Charset.forName("utf-8"))

Reference:
java 的DataOutputStream 的 writeBytes(String s) 方法在向
java String.getBytes()的問題

星期一, 12月 12, 2011

[Java] InputStreamReader

An InputStream is a binary stream, so there is no encoding. 
When you create the Reader, you need to know what character encoding to use, and that would depend on what the program you called produces (Java will not convert it in any way).


If you do not specify anything for InputStreamReader, it will use the platform default encoding, which may not be appropriate. There is another constructor that allows you to specify the encoding.


If you know what encoding to use (and you really have to know):

new InputStreamReader(process.getInputStream(), "UTF-8") // for example

[Java] 設定verbose參數顯示java application的詳細資訊

How to use verbose option while running a Java application
verbose option displays whole information while running a java application.
There are also some extensions available:
-verbose:class print information about each class loaded.
-verbose:gc Displays each garbage collection event.
-verbose:jni Report native methods used in application


設定步驟
步驟一:
$vi cataout.sh

步驟二:在JAVA_OPTS加入verbose參數

JAVA_OPTS='-server -Xms1024m -Xmx1024m -XX:MaxNewSize=256m -XX:MaxPermSize=256m -XX:+CMSParallelRemarkEnabled -XX:+CMSIncrementalMode -XX:+CMSIncrementalPacing -XX:+UseConcMarkSweepGC -verbose'


星期三, 12月 07, 2011

[Lucene] Stopwords

Lucene不支援以下的stopwords做搜尋:

"a", "an", "and", "are", "as", "at", "be", "but", "by",


"for", "if", "in", "into", "is", "it",


"no", "not", "of", "on", "or", "such",


"that", "the", "their", "then", "there", "these",


"they", "this", "to", "was", "will", "with"

Regex special characters


The patterns used in RegExp can be very simple, or very complicated, depending on what you're trying to accomplish. To match a simple string like "Hello World!" is no harder then actually writing the string, but if you want to match an e-mail address or html tag, you might end up with a very complicated pattern that will use most of the syntax presented in the table below.
PatternDescription
Escaping
\Escapes special characters to literal and literal characters to special.

E.g: /\(s\)/ matches '(s)' while /(\s)/ matches any whitespace and captures the match.
Quantifiers
{n}{n,}{n,m}*+?Quantifiers match the preceding subpattern a certain number of times. The subpattern can be a single character, an escape sequence, a pattern enclosed by parentheses or a character set.

{n} matches exactly n times.
{n,} matches n or more times.
{n,m} matches n to m times.
* is short for {0,}. Matches zero or more times.
+ is short for {1,}. Matches one or more times.
? is short for {0,1}. Matches zero or one time.

E.g: /o{1,3}/ matches 'oo' in "tooth" and 'o' in "nose".
Pattern delimiters
(pattern)(?:pattern)Matches entire contained pattern.

(pattern) captures match.
(?:pattern) doesn't capture match

E.g: /(d).\1/ matches and captures 'dad' in "abcdadef" while /(?:.d){2}/ matches but doesn't capture 'cdad'.

Note: (?:pattern) is a JavaScript 1.5 feature.
Lookaheads
(?=pattern)(?!pattern)A lookahead matches only if the preceding subexpression is followed by the pattern, but the pattern is not part of the match. The subexpression is the part of the regular expression which will be matched.

(?=pattern) matches only if there is a following pattern in input.
(?!pattern) matches only if there is not a following pattern in input.

E.g: /Win(?=98)/ matches 'Win' only if 'Win' is followed by '98'.

Note: Lookahead is a JavaScript1.5 feature.
Alternation
|Alternation matches content on either side of the alternation character.

E.g: /(a|b)a/ matches 'aa' in "dseaas" and 'ba' in "acbab".
Character sets
[characters][^characters]Matches any of the contained characters. A range of characters may be defined by using a hyphen.

[characters] matches any of the contained characters.
[^characters] negates the character set and matches all but the contained characters

E.g: /[abcd]/ matches any of the characters 'a', 'b', 'c', 'd' and may be abbreviated to /[a-d]/. Ranges must be in ascending order, otherwise they will throw an error. (E.g: /[d-a]/ will throw an error.)
/[^0-9]/ matches all characters but digits.

Note: Most special characters are automatically escaped to their literal meaning in character sets.
Special characters
^$.? and all the highlighted characters above in the table.Special characters are characters that match something else than what they appear as.

^ matches beginning of input (or new line with m flag).
$ matches end of input (or end of line with m flag).
. matches any character except a newline.
? directly following a quantifier makes the quantifier non-greedy (makes it match minimum instead of maximum of the interval defined).

E.g: /(.)*?/ matches nothing or '' in all strings.

Note: Non-greedy matches are not supported in older browsers such as Netscape Navigator 4 or Microsoft Internet Explorer 5.0.
Literal characters
All characters except those with special meaning.Mapped directly to the corresponding character.

E.g: /a/ matches 'a' in "Any ancestor".
Backreferences
\nBackreferences are references to the same thing as a previously captured match. n is a positive nonzero integer telling the browser which captured match to reference to.

/(\S)\1(\1)+/g matches all occurrences of three equal non-whitespace characters following each other.
/<(\S+).*>(.*)<\/\1>/ matches any tag.

E.g: /<(\S+).*>(.*)<\/\1>/ matches '
text
' in "text
text
text".
Character Escapes
\f\r\n\t\v\0[\b]\s,\S\w\W\d\D\b\B\cX,\xhh\uhhhh\f matches form-feed.
\r matches carriage return.
\n matches linefeed.
\t matches horizontal tab.
\v matches vertical tab.
\0 matches NUL character.
[\b] matches backspace.
\s matches whitespace (short for [\f\n\r\t\v\u00A0\u2028\u2029]).
\S matches anything but a whitespace (short for [^\f\n\r\t\v\u00A0\u2028\u2029]).
\w matches any alphanumerical character (word characters) including underscore (short for [a-zA-Z0-9_]).
\W matches any non-word characters (short for [^a-zA-Z0-9_]).
\d matches any digit (short for [0-9]).
\D matches any non-digit (short for [^0-9]).
\b matches a word boundary (the position between a word and a space).
\B matches a non-word boundary (short for [^\b]).
\cX matches a control character. E.g: \cm matches control-M.
\xhh matches the character with two characters of hexadecimal code hh.
\uhhhh matches the Unicode character with four characters of hexadecimal code hhhh.


Reference:
Regular Expressions patterns

[Alfresco] Lucene Search: Escaping special characters


今天測試開了特殊字元的帳號查看垃圾桶的檔案,在alfresco的web ui也爆炸了。
發現UID含特殊字元時,也要記得跳脫!!
you are using Lucene 1.4 or prior, there is no escape convenience utility. Instead, you must write your own. The characters that need to be escaped are: + - ! ( ) { } [ ] ^ " ~ * ? : \
Lucene 1.4 Escaping (More Complete)
// Some constants.
private static final String LUCENE_ESCAPE_CHARS = "[\\\\+\\-\\!\\(\\)\\:\\^\\]\\{\\}\\~\\*\\?]";
private static final Pattern LUCENE_PATTERN = Pattern.compile(LUCENE_ESCAPE_CHARS);
private static final String REPLACEMENT_STRING = "\\\\$0";
 
// ... Then, in your code somewhere...
String userInput = // ...
String escaped = LUCENE_PATTERN.matcher(userInput).replaceAll(REPLACEMENT_STRING);
Query query = QueryParser.parse(escaped);
// ...


Reference:
Lucene: Escaping Special Characters

星期一, 12月 05, 2011

[Javascript] Characters to escape in JSON

 $("#exec").click(function(){
  var newPW = $("#newPW").val();
  console.log("old newPW:" + newPW);
  var testPW = 
  {
    test:newPW
  }
  //escape special charactors
  console.log("JSON.stringify:" + JSON.stringify(testPW));
 });
Reference:
Characters to escape in JSON

星期三, 11月 30, 2011

[Javascript] how to get local file path from fileinput using IE8 or IE9

http://stackoverflow.com/questions/5753442/how-can-i-get-the-local-filepath-from-the-fileinput-using-javascript-in-ie9



要達到這個效果需要IE用戶開啟二項設定:

  • ie8 and ie9 必需請用戶開啟允許使用ActiveXObject 

工具->網際網路選項->安全性->自訂等級->ActiveX控制項與外掛程式->將未標示成安全的ActiveX控制項初始化並執行指令碼設定為提示(安全性考量不要設為啟用)

  • ie9必需再設定允許上傳檔案存取本機路徑(不然file upload會顯示fakepath)
工具->網際網路選項->安全性->自訂等級->雜項->將檔案上傳到伺服器包括本機路徑設為啟用

星期六, 11月 26, 2011

星期四, 11月 24, 2011

Special Characters Supported for Passwords

Name of the CharacterCharacter
at sign@
percent sign%
plus sign+
backslash\
slash/
single quotation mark'
exclamation point!
number sign#
dollar sign$
caret^
question mark?
colon:
comma.
left parenthesis(
right parenthesis)
left brace{
right brace}
left bracket[
right bracket]
tilde~
grave accent
This character is also known as the backquote character.
The grave accent cannot be reproduced in this document.
hyphen-
underscore_

Reference:

星期日, 11月 20, 2011

URL decode/encode 觀念題

做網頁傳遞中文時常會用到URL decode/encode,
混亂的 URLEncode 說明了為什麼要使用URLEncode,
有興趣可以去讀一下。

[[Javascript 茶包筆記]] 小數點運算

JavaScript 要取到小數點下的指定位數,要四捨五入時有內建的toFixed()函數可使用,

例:
var num = new Number(13.3714);
document.write(num.toFixed());
document.write(num.toFixed(1));
document.write(num.toFixed(3));
document.write(num.toFixed(10));

結果:
13
13.4
13.371
13.3714000000

星期四, 11月 03, 2011

[Javascript] URL decode encode

使用Javascript來做URL編碼,請依需求來評估使用哪一種方法!!

Javascript escape, encodeURI, encodeURIComponent Encode後的結果,整理如下表:(請參考這裡)
文字類型英文數字中文Unescaped charactersReserved charactersScore
原始字串AZaz01-_.!~*'();,/?:@&=+$#
escape後AZaz01%u5803-_.%21%7E*%27%28%29%3B%2C/%3F%3A@%26%3D+%24%23
encodeURI後AZaz01%E5%A0%83-_.!~*'();,/?:@&=+$#
encodeURI
Component後
AZaz01%E5%A0%83-_.!~*'()%3B%2C%2F%3F%3A%40%26%3D%2B%24%2

星期三, 10月 19, 2011

[jQuery Plugin] jQuery File Upload FAQ

這篇主要記錄自已使用jQuery File Upload的一些問題,如果要基本的使用方法請參考這篇:


Q1: 上傳成功時發生Empty file upload result的情況
A1:V5 的伺服端接收上傳成功的訊息後,需回傳一個JSON Array,即時只有一個上傳檔案。例如:{["uploadfilename":"helloworld.jg"]}

Q2:使用Jsp無法順利jQuery樣版無法順利套用
A2:解法在這篇討論

Uploaded filename and size is not displayed in JSP???
The plugin template use the same syntax of Expression Language (EL) used by jsp and so ${name} and ${sizef} variables are evaluated in jsp and replaced with "" and "" . To avoid this you have to replace ${name} and ${sizef} with ${"${name}"} ${"${sizef}"}.

Q3: Firefox 4 fails when uploading empty file

 can confirm this issue with the basic File Upload plugin and Firefox 5.
However this seems to be a bug in the implementation of the FormData/XHR implementation of Firefox/Gecko.
Feel free to submit a bug report here: https://bugzilla.mozilla.org
IE跟Chrome上傳0KB檔案都是正常的。

Q4: How to cancel upload queues?
 $("#yourbutton").click(function (e) {
  //invoking a click event on all the upload row cancel buttons.
  $(".cancel button").click();
 });

星期二, 10月 04, 2011

[jQuery Plugin] jQuery Templates 樣版

由於AJAX技術愈來愈多人使用,搭配回傳的JSON格式產生UI已經是非常普遍的做法,
但如果搭配樣版的觀念來動態Bind資料,想必是更省事,最近使用的jQuery-File-Upload元件,
也使用樣版來產生UI。

以下是一些學習連結:
jQuery Templates Plugin筆記1by黑暗執行緒 

[JSP] JSP頁面引用bigd-5編碼的Javascript

想不到也有人遇到過同樣的問題XD~


Reference:[Tips] 在 utf-8 頁面 使用 big5 的 Javascript 檔之前在上線網站的時候, Clark 遇到在 utf-8 的網頁下要include big5 的 js 的問題,當時出現的問題是由於big5 的 js 檔中有中文字,include 到 utf-8 的 page 上時就造成 javascript error 或文字變成亂碼,當時趕著上線,所以就選擇將原來的 js 另存一份成為 utf-8 格式的 js 。就這樣使用了到現在將近一年,最近正在改這個 js 檔時發現為什麼不延用一份共用的 js ,而去另外自已建一份呢?一測試之下終於回想到當初的原因。由於在這陣子 Clark 也處理過類似問題,得到的結論是,在語法中下 charset="big5" 就可以讓 browser 不依照該 page 的 encoding 去做解譯,所以顯示的結果就正常了!

經過修改,顯示一切正常,其他Browser也沒有發現問題,上線!

星期一, 10月 03, 2011

[Tomcat] Linux系列關掉所有java程式後啟動tomcat流程

本篇記綠同事的流程XD

//首先砍掉所有運行的java程式
>pkill -9 java

//查詢java的程序還在不在,有的話會列process id。
>pgrep java

//使用替代pgrep java類似的指令
>ps aus | grep java

//開啟tomcat
>./startup.sh

星期一, 9月 26, 2011

[Java,Tomcat] 第一次使用DBCP就上手

本篇文章記錄安裝Tomcat的DBCP(Data Base Connection Pool)過程

測試環境:
Apache Tomcat/6.0.29
JVM1.6.0_21-b06
Connector/J 5.1.5 (the official JDBC Driver)mysql-connector-java-5.1.5-bin.jar

星期五, 9月 23, 2011

[jQuery plugin] jQuery Validator addMethod always return false

今天在做驗證帳號是否已存在的時遇到的問題。 當觸發驗證規則時,由於是非同步的呼叫,會造成Validator總是會回傳驗證失敗。 只要將jQuery 預設的ajax方法,多帶入async:false即可。


$.validator.addMethod( "conflictaccount" , function(value,element){ console.log("account:" + value); var isValidate = true; $.checkUserAccount( { async:false,//avoid value of return is false endpoint : HOSTNAME, ticket : TICKET, uid: value, callback:function(data){ if(data.verify){ //confilct account // console.log("confilct"); isValidate = false; }else{ // console.log("Not Conflict"); isValidate = true; } } }); // console.log("isValidate:" + isValidate); return isValidate; });

 註:$.checkUserAccount裡面是call $ajax的方法。

星期四, 9月 08, 2011

[Linux] Tomcat logs

Tip:/APP/TOMCAT安裝目錄

使用Putty查看Tomcat logs


1.進入logs directory
$cd /APP/TOMCAT/logs

2.監看logs
#持續刷新logs,缺點看的數量會被putty的視窗限制住
$tail -f catalina.out

or

#-n 加行數查看
$tail -n 1000 catalina.out

or

#加上grep搜尋
$tail -n 1000 catalina.out | grep 搜尋的字

清空所有Logs
$echo > catalina.out

星期二, 9月 06, 2011

[Eclipse] 設定字型大小

Eclipse設定字型大小也太難找了吧Orz
步驟:
Preferences->General->Appearance->Colors and Fonts->Basic->Text Font(達陣了Q_Q)



星期日, 9月 04, 2011

[PHP] Appserv 重新設定port

當你的windows上已經讓IIS佔用80 port之後,
就正常無法運行Apache(TOMCAT預設是佔用8080)。


所以必需重新設定Apache使用的port。
步驟如下:

第一步:俢改httpd.conf
打開AppServ > Apache2.2 > conf > httpd.conf 
修改Listen的80
#Listen 12.34.56.78:80
Listen 80 



第二步:重新啟動Apache
改後去程式集 Appserv Control Server by Service > Apache Restart

[PHP] Facebook login 整合

整理一些有關於facebook的整合相關文章:

http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/
PHP SDK & Graph API base Facebook Connect Tutorial
[教學] Facebook API PHP SDK 基本篇. Facebook API PHP SDK Basic introduce.
Facebook Connect 搭配 API 提供帳號管控教學

星期五, 9月 02, 2011

[jQuery] 錯誤元素呼叫.html()引起的"對方法或內容存取發出未預期的呼叫"

今天在做多國語言切換的時候遇到的怪異bug
起因原來是呼叫.html取代語言檔字串時,目標元素不存在。
 <b>頁面配置:
</b> <label class="profile_add_title" for="name">Name</label> <input id="organization" name="organization" type="text" class="profile_input" />

//如果元素不支援.html方法時,會導致呼叫方法錯誤
$("#organization").prev().html(global_company_name);

星期一, 8月 22, 2011

[Eclipse] 關掉Java Script Validator

Eclipse一直跳出Javascript Validator擾民的訊息,可以從點選專案後按Properties->Builders->JavaScript Validator(uncheck)就可以了!!


星期一, 8月 08, 2011

Hp pavilion tx 1000 drivers for win7

最近幫朋友重灌Hp pavilion tx 1000筆電,由於是老電腦找Drivers就特別麻煩,
有需要的參考看看,不過目前的FN鍵跟觸控面版還是Driver不了。

星期日, 8月 07, 2011

[Java] System.properties


From System Properties you can find information about the operating system, the user, and the version of Java.
The property names (keys) and values are stored in a Properties structure. (See Properties). A Properties object can also be used to store your own program properties in a file.


Reference:
Java: System Properties

星期五, 8月 05, 2011

[Java] Servlet file upload filename encoding (中文亂碼)

解決中文檔名亂碼問題:在init ServletFileUpload呼叫setHeaderEncoding指定編碼為utf-8,
就能正確取出中文了

ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
List items = null;
   try {
    items = upload.parseRequest(request);
//    System.out.println("item is added.");
   } catch (FileUploadException e) {
    System.out.println("FileUploadException:" + e.getMessage());
   }
   if (items != null) {
//    System.out.println("items count:" + items.size());
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
                                  FileItem item = iter.next();
                                  String filename = item.getName();
                                }
                        }
Reference:
servlet file upload filename encoding

星期四, 7月 28, 2011

[C#] HttpWebRequest request limitation

最近實作多執行緒上傳檔案的測試工具時,
發現不管執行幾個執行緒同時只會有二個連線數存在。
這是.net預設的連線數,透過以下設定即可。
ServicePointManager.DefaultConnectionLimit = 10;
網路上有人建議最大連線數不要超過1024,最好的效果是512。
另外也可以從app.config來設定最大連線數

硬碟單位換算


單位換算問題:適用於各語言的實作XD
10 MB = 10485760 Bytes

Explanation: 10 MB = 10*1024 KB = 10*1024*1024 Bytes = 10485760 Bytes

As we have,

1 KB = 1024 Bytes

1 MB = 1024 KB


Read more: 

星期二, 7月 19, 2011

[jQuery Plugin] 第一次用jQuery Validator就上手

常用到的客戶端的表單欄位驗證,在此簡單記錄一下:
本測試使用v1.8.1

[Java] Resize Image as JPG

簡單的影像Resize程式

public class ResizeImage {

 static public byte[] resizeImageAsJPG(byte[] pImageData, int pMaxWidth)
   throws IOException {

  // Create an ImageIcon from the input image byte[]
  ImageIcon imageIcon = new ImageIcon(pImageData);
  int width = imageIcon.getIconWidth();
  int height = imageIcon.getIconHeight();

  // If the image is larger than the max width, we need to resize it
  if (pMaxWidth > 0 && width > pMaxWidth) {
   // Determine the shrink ratio
   double ratio = (double) pMaxWidth / imageIcon.getIconWidth();
   height = (int) (imageIcon.getIconHeight() * ratio);
   width = pMaxWidth;
  }

  // Create a new empty image buffer to "draw" the resized image into
  BufferedImage bufferedResizedImage = new BufferedImage(width, height,BufferedImage.SCALE_SMOOTH);
  // Create a Graphics object to do the "drawing"
  Graphics2D g2d = bufferedResizedImage.createGraphics();
  g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);
  // Draw the resized image
  g2d.drawImage(imageIcon.getImage(), 0, 0, width, height, null);
  g2d.dispose();
  // Now our buffered image is ready
  // Encode it as a JPEG
  ByteArrayOutputStream encoderOutputStream = new ByteArrayOutputStream();
  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(encoderOutputStream);
  encoder.encode(bufferedResizedImage);
  byte[] resizedImageByteArray = encoderOutputStream.toByteArray();
  return resizedImageByteArray;
 }
}

[jQuery] File upload using AJAX form

最近使用jQuery Form Plug & jQuery File Upload上傳檔案,如果將Server Response的content-type設定application/json的話,因為元件上傳使用iframe來達到ajax form的效果,因此在Firefox和IE瀏覽器會跳出下載的Dialog。如果要回傳json格式來交換資料的話,只能將content-type設定text/plain或text/html,等接到ajax callback事件後,再將json的字串利用JSON.parser()轉換到json object即可。


後紀:使用text/plain會被多加pre element進去

Reference:Frequently Asked Questions
Internet Explorer prompting to download a file after the upload completes

The file upload plugin makes use of an Iframe Transport module for browsers like Microsoft Internet Explorer and Opera, which do not yet supportXHR file uploads.
Iframe based uploads require a Content-type of text/plain or text/html for the JSON response - they will show an undesired download dialog if the iframe response is set to application/json.
Please have a look at the Content-Type Negotiation section of the Setup instructions.

星期五, 7月 15, 2011

[C#] Settings

To Write and Persist User Settings at Run Time
  1. Access the user setting and assign it a new value, as shown in the following example:
    Properties.Settings.Default.myColor = Color.AliceBlue;
    
  2. If you want to persist changes to user settings between application sessions, call the Savemethod, as shown in the following code:
    Properties.Settings.Default.Save();

星期一, 7月 11, 2011

[Java] Keytool 相關蒐集

[Java] 實作HTTPS Request

最近的專案為了確保網路資料傳輸的安全性,使用了SSL來加密,
原本實作的RESTful Client(Java HttpsURLConnection)模擬request時,伺服器回應了以下錯誤:

javax.servlet.ServletException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:418)
 com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
 com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Google了一下找到了這篇文章:

其他你感興趣的文章

Related Posts with Thumbnails