2012年8月10日 星期五

[Linux] 使用 Dropbox Command Line @ Ubuntu 12.04 server

今天看到一篇文章談論關於 team 合作的模式,其中提及 Dropbox 的地位,例如大家組隊參加比賽,在比賽過程中有不少工作的委派跟追蹤,這時候該如何進行?其中有一個微小卻很重要的就是檔案的交換,這時候使用 dropbox 共享某個目錄就顯得很方便,甚至大家可以自定 filename 或 dirname 當做一個 notification,經由 dropbox 同步功能、通知功能就方便達成啦!


講了那麼多,我只是要用在虛擬機器上 XDD 這樣機器掛了,至少一些工作的檔案或記錄,可以有多幾版本 sync 到 dropbox 啦,以免哪天機器突然下線欲哭無淚。申請 dropbox 免費帳號 2GB 空間實在很夠用了!更可每一台虛擬機器申請一個帳號(可避免關鍵帳密擺在虛擬機器上),接著常用帳號分享目錄給各台的功能。此外,搭配 GMail 又可以放大絕(YourAccount+VM1@gmail.com)。另外,在工作站上,又可以直接開很多個 user 跑 dropbox 喔。


設定 Dropbox @ Ubuntu 12.04 64bit server:


$ wget -O dropbox.x86.tar.gz "http://www.dropbox.com/download/?plat=lnx.x86"
$ tar -xvf dropbox.x86.tar.gz
$ mv .dropbox-dist/ ~/
$ ~/.dropbox-dist/dropboxd
/home/user/.dropbox-dist/dropboxd: 10: exec: /home/user/.dropbox-dist/dropbox: not found
$ file ~/.dropbox-dist/dropbox
/home/user/.dropbox-dist/dropbox: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.8, stripped
$ sudo apt-get install ia32-libs
$ ~/.dropbox-dist/dropboxd
This client is not linked to any account...
Please visit https://www.dropbox.com/cli_link?host_id=xxxxxxxxxxxxxxxxx&cl=en_US to link this machine.



Client successfully linked, Welcome Bbs!


如果 OS 環境也是 64Bit 的,那就跟我一樣安裝一下 ia32-libs 即可,當執行 ~/.dropbox-dist/dropbox 時,顯示 This client is not linked to any account... 並給予一支 url 時,就只需開瀏覽器去瀏覽那個 url ,並用你將綁定在機器的帳號登入即可,如此一來,成功後會顯示 Client successfully linked, Welcome Bbs! 訊息。


經由上述流程後,已經設定好 dropbox command line 的使用了,在家目錄可以看到 ~/Dropbox 跟 ~/.dropbox 兩個目錄,其中 ~/Dropbox 就是用來同步的目錄,而 ~/.dropbox 則是綁定帳號的相關資訊,如果要用其他帳號來綁定的話,請刪掉這兩個目錄吧。


設定一下開機自動啟動:


網路上一堆人參考 http://wiki.dropbox.com/TipsAndTricks/TextBasedLinuxInstall/UbuntuStartup 和 http://wiki.dropbox.com/TipsAndTricks/TextBasedLinuxInstall 等等,但我現在都連不上無法看原始的 script


故暫時參考 modified script from here http://wiki.dropbox.com/TipsAndTricks/TextBasedLinuxInstall/UbuntuStartup,這 script 做的事就是找出有哪些 user 的家目錄中有 ~/.dropbox-dist/dropbox ,找到後把它跑起來,如此而已。而這個修改的版本嘛,還滿通用的,只需設定一個 group 名為 dropbox ,並把機器上使用的帳號加入此 group 即可,無需修改 script 囉。


$ sudo cp dropbox-script /etc/init.d/dropbox
$ sudo chmod +x /etc/init.d/dropbox
$ sudo /etc/init.d/dropbox status
Status of dropbox ...
$ sudo update-rc.d dropbox defaults 
Adding system startup for /etc/init.d/dropbox ...
/etc/rc0.d/K20dropbox -> ../init.d/dropbox
/etc/rc1.d/K20dropbox -> ../init.d/dropbox
/etc/rc6.d/K20dropbox -> ../init.d/dropbox
/etc/rc2.d/S20dropbox -> ../init.d/dropbox
/etc/rc3.d/S20dropbox -> ../init.d/dropbox
/etc/rc4.d/S20dropbox -> ../init.d/dropbox
/etc/rc5.d/S20dropbox -> ../init.d/dropbox
$ sudo /etc/init.d/dropbox start
Starting dropbox...
$ sudo /etc/init.d/dropbox status
Status of dropbox ...
dropboxd for USER username: running (pid #####)


最後,如需要更豐富的 dropbox 運行資訊,可以試試 http://www.dropbox.com/download?dl=packages/dropbox.py 這隻程式吧。


2012年7月18日 星期三

Android 開發教學筆記 - 使用 Thread 和 Handler 的差別

簡單的說,不需 UI 更新的,可以挑 Thread 來使用,需要動到 UI 的操作的,請用 Handler 的方式處理。


2012年7月5日 星期四

Android 開發筆記 - 批次、大量設定按鈕事件偵測(setOnClickListener)

最近的案子很特別,除了一堆 Activity 外,每一個 Activity 裡頭又有一堆 Button/ImageButton 要處理,如果是依照一般教學文:


Button b = null;
if( ( b = (Button)findViewById( R.id.button01) ) != null )
        b.setOnClickListener( new Button.OnClickListener(){ /* ... */ } );
if( ( b = (Button)findViewById( R.id.button02) ) != null )
        b.setOnClickListener( new Button.OnClickListener(){ /* ... */ } );
...


假設有 20~30 個按鈕,就得用 findViewById 處理 20~30 次,程式碼就又臭又長。另一種作法則是把每個 Button/ImageButton 都設定為同一個 Button.OnClickListener 來管理,透過 View.getId() 來偵測,的確可以省記憶體,但還是不免要把 layout 上一堆按鈕都先 findViewById 一下,後來跟同事閒聊時,恰好提到用動態新增按鈕的方式,於是被 loop 關鍵字提醒一下,就來惡搞了:


void initOnClickListener() {


        int my_ids[] = {
                R.id.button01, R.id.button02, R.id.button03, ...
        };


        Button b = null;
        for( int i=0 ; i< ids.length ; ++i )
                if( ( b = (Button)findViewById( my_ids[i]) ) != null )
                        b.setOnClickListener(this);
}


public void onClick(View v) {
        switch( v.getId() ) {
                case R.id.button01:
                        break;
                case R.id.button02:
                        break;
                // ...
        }
}


其中的 this 就是指 MyActivity extends Activity implements OnClickListener,如此一來可以用最簡短的程式碼,很方便的初始化 layout 上頭的按鈕,也不用每個按鈕都 new Button.OnClickListener 出來,也會省記憶吧。這樣管理 Button/ImageButton 還滿方便的,只需把要偵測的按鈕,將其 R.id.name 擺在 array 裡頭,跑 loop 來解決就好啦。如果有用  PagerAdapter/ViewPager 實作 iOS PageControl 的話,更可以用多階層來管理:


final int cntView = 3;
int my_ids[][] = {
        {
                R.id.view1_btn1 , R.id.view1_btn2 , R.id.view1_btn3, ...
        } , 
        {
                R.id.view2_btn1 , R.id.view2_btn2 , R.id.view2_btn3, ...
        } ,
        {
                R.id.view3_btn1 , R.id.view3_btn2 , R.id.view3_btn3, ...
        }
}; 

for( int i=0 ; i<cntView ; ++i ) {
        for( int j=0 ; j<my_ids[i].length ; ++j ) {
                if( ( b = (Button)mPageView.get(i).findViewById( my_ids[i]) ) != null )
                        b.setOnClickListener( this );
        }


其中 mPageView 用來記錄每個 page 的 Activity 囉。


2012年7月4日 星期三

Android 開發筆記 - HTTP、HTTPS、GET、POST、Cookie

寫 Mobile app 不免要網路連線一下,這時候最簡易的方式就是像 php 的 file_get_contents 函數,只要呼叫一下,就得到想要的東西。然而,在測試 https 時,發現對方憑證並非經過第三方認證的,因此噴出錯誤訊息:android javax.net.ssl.SSLPeerUnverifiedException: No peer certificate,這資安保護的確還不錯,但對開發、測試實在不方便,在網路上有找到的解法是實作一個 SSLSocketFactory 來解決,雖然不知是不是正解,但至少可以 work 了 :P (總覺得應該要能某個參數設定一下就行,就像 php curl 的 CURLOPT_SSL_VERIFYPEER 和 CURLOPT_SSL_VERIFYHOST 參數)


發送 http GET request:


//
// List<NameValuePair> params = new LinkedList<NameValuePair>(); // ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("a", "1"));
// params.add(new BasicNameValuePair("b", "2"));
// System.out.println( get_url_contents( "http://www.google.com.tw" , null )  );
// System.out.println( get_url_contents( "http://www.google.com.tw" , params )  );
//
String get_url_contents( String url , List<NameValuePair> params ) {
        try {
              HttpClient client = new DefaultHttpClient();
              HttpResponse response = client.execute( new HttpGet( params == null || params.size() == 0 ? url : url + "?" + URLEncodedUtils.format(params, "utf-8") ) );
              HttpEntity result = response.getEntity();
              if( result != null ) {
                     //return EntityUtils.toString(result); // 有編碼問題
                     InputStream mInputStream = result.getContent();
                     String out = getStringFromInputStream(mInputStream);
                     mInputStream.close();
                     return out;
              }
       } catch (Exception e) {
              e.printStackTrace();
       }
       return null;
}


發送 http POST request:


String post_url_contents( String url, List<NameValuePair> params ) {
       try {
              HttpClient client = new DefaultHttpClient();
              HttpPost mHttpPost = new HttpPost(url);
              if( params != null && params.size() > 0 )
                     mHttpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
              HttpResponse response = client.execute(mHttpPost);
              HttpEntity result = response.getEntity();
              if( result != null ) {
                      //return EntityUtils.toString(result); // 有編碼問題
                      InputStream mInputStream = result.getContent();
                      String out = getStringFromInputStream(mInputStream);
                      mInputStream.close();
                      return out;
              }
       } catch (Exception e) {
              e.printStackTrace();
       }
       return null;
}


使用 Cookie 的方式:


// CookieStore cookieStore = new BasicCookieStore();
String get_url_contents( String url , List<NameValuePair> params , CookieStore cookieStore ) {
        try {
              HttpClient client = new DefaultHttpClient();
              HttpResponse response = null;
              if( cookieStore == null )
                     response = client.execute( new HttpGet( params == null || params.size() == 0 ? url : url + "?" + URLEncodedUtils.format(params, "utf-8") ) );
              else {
                     HttpContext mHttpContext = new BasicHttpContext();
                     mHttpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
                     response = client.execute( new HttpGet( params == null || params.size() == 0 ? url : url + "?" + URLEncodedUtils.format(params, "utf-8") ) , mHttpContext );
              }
              HttpEntity result = response.getEntity();
              if( result != null ) {
                      //return EntityUtils.toString(result);  // 有編碼問題
                      InputStream mInputStream = result.getContent();
                      String out = getStringFromInputStream(mInputStream);
                      mInputStream.close();
                      return out;
              }
       } catch (Exception e) {
              e.printStackTrace();
       }
       return null;
}


其他:


String getStringFromInputStream(InputStream in) {
       byte []data = new byte[1024];
       int length;
       if( in == null )
              return null;
       ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
       try {
              while( (length = in.read(data)) != -1 )
                     mByteArrayOutputStream.write(data, 0, length);
       } catch (IOException e) {
              e.printStackTrace();
       }
       return new String(mByteArrayOutputStream.toByteArray());
}


解決 android javax.net.ssl.SSLPeerUnverifiedException: No peer certificate:


程式碼:


import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;


public class MySSLSocketFactory extends SSLSocketFactory {
        SSLContext mSSLContext = SSLContext.getInstance("TLS");


        @Override
        public Socket createSocket() throws IOException {
                return mSSLContext.getSocketFactory().createSocket();
        }


        @Override
        public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
                return mSSLContext.getSocketFactory().createSocket(socket, host, port, autoClose);
        }


        public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
                super(truststore);

                TrustManager mTrustManager = new X509TrustManager() {


                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }


                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }


                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                                return null;
                        }
                };
                mSSLContext.init(null, new TrustManager[] { mTrustManager }, null);
        }
        public static HttpClient createMyHttpClient() {
                try {
                        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                        trustStore.load( null, null);

                        SSLSocketFactory mSSLSocketFactory = new MySSLSocketFactory(trustStore);
                        mSSLSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                        HttpParams params = new BasicHttpParams();
                        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
                        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

                        SchemeRegistry registry = new SchemeRegistry();
                        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                        registry.register(new Scheme("https", mSSLSocketFactory, 443));

                        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
                        return new DefaultHttpClient(ccm, params);
                } catch (KeyStoreException e) {
                        e.printStackTrace();
                } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                } catch (CertificateException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } catch (KeyManagementException e) {
                        e.printStackTrace();
                } catch (UnrecoverableKeyException e) {
                        e.printStackTrace();
                }
                return new DefaultHttpClient();
        }
}


使用:


//HttpClient client = new DefaultHttpClient();
HttpClient client = MySSLSocketFactory. createMyHttpClient();


參考資料:


Android Series: GET, POST and Multipart POST requests
android javax.net.ssl.SSLPeerUnverifiedException: No peer certificate


2012年7月3日 星期二

Android 開發筆記 - 模仿 iOS UINavigationController 效果

為了給使用者有一致性的體驗,在 Android 環境上,實作 iOS UINavigationController 效果。


實作的方式很...直觀,就是每個 Activity 最上頭都擺在一個區域(header)來達成啦 XD


例如 header.xml:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="@drawable/background">
        <FrameLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:gravity="center"
                android:background="@null">

               <TextView
                       android:layout_width="fill_parent"
                       android:layout_height="fill_parent"
                       android:text="@string/title"
                       android:gravity="center"
                       android:textAppearance="?android:attr/textAppearanceMedium" />

               <ImageButton
                       android:id="@+id/btn_right"
                       android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:src="@drawable/btn_right"
                       android:background="@null"
                       android:contentDescription="@null"
                       android:layout_gravity="center_vertical|right"/>

        </FrameLayout>
</LinearLayout>


而其他的 Activity layout 可以在開頭就用類似方式 include 進來:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:gravity="center_horizontal"
       android:orientation="vertical">

       <include android:id="@+id/header"
              layout="@layout/header"
              android:layout_height="wrap_content"
              android:layout_width="fill_parent"/>
       …
</LinearLayout>