2012年6月15日金曜日

git pushでHTTP 411エラーが出たときの対処法

git push をおこなったとき、サーバーから HTTP ステータスコード 411 が返され、失敗してしまうことがある。

[図1] TortoiseGit でのエラー表示例

[図2] Eclipse でのエラー表示例

HTTP ステータスコード 411 の定義には「The server refuses to accept the request without a defined Content- Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message.」と書かれている。つまり、このステータスコードは、クライアントの HTTP リクエストに Content-Length ヘッダーが付いていないことを理由としてサーバーがリクエストを拒否する場合に返されるのであるが、git push のときにこのステータスコードが返される原因は、push しようとしているデータ量が多過ぎることにある。


この問題の対処法は、git の設定値 http.postBuffer の値を大きくすることである。例えばこの値を 100MB (100 * 1024 * 1024 = 104857600) にするには、コマンドラインでは次のように打ち込む。

git config http.postBuffer 104857600

TortoiseGit の GUIでおこなうには、エクスプローラのコンテキストメニューから、TortoiseGit → Settings で TortoiseGit の設定ダイアログを表示し、Git → Config → Edit local git/config で設定ファイルを開き、http.postBuffer に関する設定を追記する。

[http]
  postBuffer = 104857600

[図3] git 設定ファイルに http.postBuffer を追記

2012年4月17日火曜日

Get a file's content as String in Java

public static String toString(File file, Charset charset) throws IOException
{
    if (file == null)
    {
        // Error. 'file' argument is mandatory.
        throw new IllegalArgumentException("file is null.");
    }

    if (charset == null)
    {
        // Use the default charset of the platform.
        charset = Charset.defaultCharset();
    }

    if (Integer.MAX_VALUE < file.length())
    {
        // The file size is too big.
        throw tooBig(file, null);
    }

    // InputStream to read the content of the file from.
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));

    try
    {
        // Create a byte array having the same size as the file.
        byte[] content = new byte[(int)file.length()];

        // Read all the bytes of the file into the byte array.
        in.read(content);

        // Convert the byte array into a String instance.
        return new String(content, charset);
    }
    catch (OutOfMemoryError e)
    {
        // new byte[] (or new String) failed. The file size is too big.
        throw tooBig(file, e);
    } 
    finally
    { 
        try
        {
            in.close();
        }
        catch (IOException e)
        {
        }
    }
}

private static IOException tooBig(File file, Throwable cause)
{
    String format = "The file '%s' is too big (%,d bytes).";

    String message = String.format(format, file.getAbsolutePath(), file.length());

    if (cause != null)
    {
        return new IOException(message, cause);
    }
    else
    {
        return new IOException(message);
    }
}


An excerpt from the online Java API document of java.nio.channels.FileChannel#map method:

For most operating systems, mapping a file into memory is more expensive than reading or writing a few tens of kilobytes of data via the usual read and write methods. From the standpoint of performance it is generally only worth mapping relatively large files into memory.



After that, I noticed readFileToString(File file, Charset encoding) method of FileUtils class of Apache Commons IO provides the same functionality (although I don't know its implementation). The wheel again... I should check Apache Commons first before starting something.



ファイルの内容をStringとして取得する (Java)

public static String toString(File file, Charset charset) throws IOException
{
    if (file == null)
    {
        // エラー。file 引数は必須。
        throw new IllegalArgumentException("file が null です。");
    }

    if (charset == null)
    {
        // プラットフォームのデフォルトのキャラクターセットを使う。
        charset = Charset.defaultCharset();
    }

    if (Integer.MAX_VALUE < file.length())
    {
        // ファイルサイズが大き過ぎる。
        throw tooBig(file, null);
    }


    // ファイルの内容を読み込むための InputStream
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));

    try
    {
        // ファイルと同じサイズを持つ byte 配列を作成する。
        byte[] content = new byte[(int)file.length()];

        // ファイルの全てのバイトを byte 配列に読み込む。
        in.read(content);

        // byte 配列を String に変換する。
        return new String(content, charset);
    }
    catch (OutOfMemoryError e)
    {
        // new byte[] (もしくは new String) が失敗した。ファイルサイズが大き過ぎる。
        throw tooBig(file, null);
    }
    finally
    {
        try
        {
            in.close();
        }
        catch (IOException e)
        {
        }
    }
}


private static IOException tooBig(File file, Throwable cause)
{
    String format = "ファイル「%s」は大き過ぎます (%,d バイト)";

    String message = String.format(format, file.getAbsolutePath(), file.length());

    if (cause != null)
    {
        return new IOException(message, cause);
    }
    else
    {
        return new IOException(message);
    }
}


java.nio.channels.FileChannel#map メソッドのオンライン Java API ドキュメントからの抜粋:

ほとんどのオペレーティングシステムでは、ファイルをメモリーにマッピングするほうが、通常の read メソッドまたは write メソッドを使って数十キロバイトのデータの読み込みまたは書き込みを行うよりも負荷が大きくなります。性能を重視するなら、比較的大きめのファイルだけをマッピングすることをお勧めします。



その後、Apache Commons IO の FileUtils クラスの readFileToString(File file, Charset encoding) メソッドが同じ機能を提供していることを知った(実装はどうなっているか知らないけど)。車輪開発してしまった。これからは、何かやるときは Apache Commons を調べてからにしよう。

2012年1月11日水曜日

AndroidのHandlerクラスの使い勝手を良くする

Android の Handler クラスの使い勝手が悪いので、改善してみる。

UI 関連の処理をおこないたい場合、(Handler クラスのデフォルトコンストラクタを使うと)「UI スレッド内で Handler インスタンスを作成し、Runnable インスタンスを別途作成して当該 Handler インスタンスの post メソッドに渡す」というコーディングが必要で、そのままコーディングすると次のようになるが、

// UI スレッド
//
// Handler インスタンスを作る。別スレッドで使うというユースケースが
// 大半なので、final を付けることが多くなる。
final Handler handler = new Handler();

// UI スレッドではない別のスレッド
//
// UI に関連する処理をスケジュールする。
handler.post(new Runnable() {
    public void run() {
        // UI スレッドで実行する処理を記述する。
    }
});

面倒なので、「(1) 常に UI スレッドに紐付けられ、(2) 自クラスで Runnable インターフェースを実装する」Handler クラスのサブクラスを次のように実装してみる。

public class UiHandler extends Handler implements Runnable
{
    public UiHandler()
    {
        // Looper.getMainLooper() で UI スレッドの Looper を取得する。
        super(Looper.getMainLooper());
    }

    public UiHandler(Handler.Callback callback)
    {
        // Looper.getMainLooper() で UI スレッドの Looper を取得する。
        super(Looper.getMainLooper(), callback);
    }

    public boolean post()
    {
        // 自分で Runnable インターフェースを実装しているので、
        // post メソッドに this を渡すことができる。
        return post(this);
    }

    public boolean postAtFrontOfQueue()
    {
        return postAtFrontOfQueue(this);
    }

    public boolean postAtTime(Object token, long uptimeMillis)
    {
        return postAtTime(this, token, uptimeMillis);
    }

    public boolean postAtTime(long uptimeMillis)
    {
        return postAtTime(this, uptimeMillis);
    }

    public boolean postDelayed(long delayMillis)
    {
        return postDelayed(this, delayMillis);
    }

    public void run()
    {
        // UI スレッドで実行する処理を記述する。
        // サブクラスでオーバーライドすべき。
    }
}

これにより、「任意のスレッド内で」(←面倒削減ポイント)当該サブクラスのインスタンスを作成できる上、Handler と Runnable を別々に管理する必要もなくなり、下記のようなコーディングが可能となる。

new UiHandler() {
    public void run() {
        // UI スレッドで実行する処理を記述する。
    }
}.post();

2011年12月17日土曜日

servlet-api.jar and Servlet API javadoc

Apache Tomcat packages contain servlet-api.jar.


Servlet API 3.0
http://tomcat.apache.org/download-70.cgi (Tomcat 7.0)
apache-tomcat-7.0.23/lib/servlet-api.jar
Javadoc

Servlet API 2.5
http://tomcat.apache.org/download-60.cgi (Tomcat 6.0)
apache-tomcat-6.0.35/lib/servlet-api.jar
Javadoc

Servlet API 2.4
http://tomcat.apache.org/download-55.cgi (Tomcat 5.5)
apache-tomcat-5.5.34/common/lib/servlet-api.jar
Javadoc

2011年12月16日金曜日

無料でプライベートGitリポジトリーを作り放題のクラウドストレージ

Windows Live Mesh を使えば、無料でクラウド上の 5GB の領域に、プライベートリポジトリ数無制限で GIT プロジェクト群をホスティングできることに気付いた。手順は、大雑把に言うと次の通り。

  1. ローカルマシン上に作業用 Git リポジトリーを作成する。
  2. 1.で作成したリポジトリから、ローカルマシン上にベアリポジトリーを作成する。
  3. 2. で作成したベアリポジトリーを、Windows Live Mesh で SkyDrive と同期する設定にする。

Eclipse で作業する場合の具体的な手順は次のとおり。


作業用 Git リポジトリーの作成

(1) 「ファイル」→「新規」から、新しいプロジェクトを作成する。ここでは、myproject という名前のプロジェクトを作成することにする。

(2) プロジェクト名を右クリックし、「チーム」→「プロジェクトの共用...」と進み、表示された「プロジェクトの共用」ダイアログで Git を選択し、「次へ」ボタンを押す。



(3) 「Git リポジトリー構成」ダイアログで、リポジトリー指定欄の右にある「作成...」ボタンを押す。

(4) 「Git リポジトリーの作成」ダイアログで、作成するリポジトリーを指定する。ここでは、C:\Users\Takahiko\Dev\Git フォルダ内に myproject という名前で作成することにする。



(5) 「Git リポジトリー構成」ダイアログに戻るので、「完了」ボタンを押す。



(6) プロジェクト名を右クリックし、「チーム」→「コミット...」と進み、コミットする。




ベアリポジトリーの作成

ここでは、C:\Users\Takahiko\Documents\Cloud\Dev\Git\myproject.git というベアリポジトリーを作成することにする。Cygwin で作業する場合は次のようになる。

(7) ベアリポジトリー用のフォルダーを作成して、そこに移動する。

mkdir -p /cygdrive/c/Users/Takahiko/Documents/Cloud/Dev/Git
cd /cygdrive/c/Users/Takahiko/Documents/Cloud/Dev/Git

(8) --bare オプションをつけて git clone を実行する。(ベアリポジトリー名の末尾に .git を付けるのは慣習)

git clone --bare /cygdrive/c/Users/Takahiko/Dev/Git/myproject myproject.git

(9) 作業用リポジトリーがベアリポジトリーを参照するように設定する。具体的には、作業用リポジトリーフォルダーをエクスプローラーで開き、右クリックでコンテキストメニューを表示して「TortoiseGit」→「Settings」と進み(TortoiseGitインストール済みと仮定)、Git → Remote で、リモートの設定をおこなう。Remote 名は何でもいいが無難に origin、URL にはベアリポジトリーのパスを指定する。

Remote: origin
URL: C:/Users/Takahiko/Documents/Cloud/Dev/Git/myproject.git



(10) Eclipse に戻り、リモート設定がうまくいっているかを試す。具体的には、プロジェクト名を右クリックし、「チーム」→「アップストリームへプッシュ」をおこない、エラーが出なければ OK。現時点では [up to date] と表示されるはず。




Windows Live Mesh で同期する

(11) Windows Live Mesh をインストールする。(Windows Live ID [無料] を取得しておく必要がある)

(12) Windows Live Mesh を起動し、ベアリポジトリーを SkyDrive と同期するように設定にする。





上記の作業後、SkyDrive に行って「同期済みフォルダーの表示」をおこなうと、ベアリポジトリーが SkyDrive にアップロードされていることが分かる。





アップロードされているベアリポジトリーは他者からは見えていないはずだからプライベート・リポジトリーである。かつ、この方法を使うと、容量制限 5GB に達しない限り、プライベート・リポジトリーの数に制限はない。加えて、まだ検証できてはいないが、「同期したファイルやフォルダーを共有する」機能を使えば、最大9名と一つのベアリポジトリーを共有して作業できる。これらのことが無料でできるのだから、ありがたい。

Stackoverflow で商用プロジェクト用の GIT リポジトリーホスティングサービスでベストなものはどれか、という議論があり、

Best Git repository hosting for a commercial project?
http://stackoverflow.com/questions/109440/best-git-repository-hosting-for-a-commercial-project

GitHub という選択が優勢のようだが、GitHub の料金プランの一つ Medium は、「プライベート・リポジトリー数 20 で、共同作業者 10 名」で毎月 22 ドルであり、みんなが言うように、高い。

Stackoverflow で挙げられている選択肢のいずれよりも、Windows Live Mesh という選択肢のほうが良いと思う。何と言っても、無料でクラウド上にプライベート Git リポジトリーを作りたい放題。



その後、BitBucket というサービスを知った。共同作業の人数が少ないうちは、プライベートリポジトリーを作りたい放題。これで十分。

http://bitbucket.org/

2011年12月14日水曜日

Eclipse EGit の Auth fail エラーへの対処法

Eclipse の EGit で Team → Push to Upstream がうまくいかず、だいぶ悩んだ。次のようなエラーメッセージが出て、push できなかった。

An internal Exception occurred during push: ssh://ユーザー@ホスト/GITリポジトリ: Auth fail

試行錯誤していたところ、この問題は Eclipse を Windows で使っている場合に起こることを知った。

Auth fail - jGit on Eclipse with Windows
http://blog.phlegx.com/2009/06/17/auth-fail-jgit-on-eclipse-with-windows/

Windows 7 64-bit 版で Eclipse 3.7 (Indigo) を使っている私のケースでは、次の手順を踏むことにより問題を解決できた。


(1) 対象ホスト用の秘密鍵を含むファイルを準備する。

ファイル名の例:
C:\Users\ユーザー名\.ssh\id_rsa


(2) ホームディレクトリの .ssh ディレクトリの下に config というファイルを作成する。

ファイル名の例:
C:\Users\ユーザー名\.ssh\config


(3) config ファイルに次の内容を記述する。

Host = ホスト名
IdentityFile = 秘密鍵ファイル

ファイル内容の例:
Host = example.com
IdentityFile = C:\Users\ユーザー名\.ssh\id_rsa

場合によっては、上記に加えて環境変数 HOME を明示的に「C:\Users\ユーザー名」と設定しておく必要があるかもしれない。

2011年11月29日火曜日

Solution for gdata-java-client's SAXNotRecognizedException

You will see SAXNotRecognizedException if you try to retrieve data from YouTube using gdata-java-client.

gdata-java-client
http://code.google.com/p/gdata-java-client/

The root cause is reported in detail as Issue 9493.

http://code.google.com/p/android/issues/detail?id=9493

The first solution that came to my mind is to replace SAXParserFactory using the system property "javax.xml.parsers.SAXParserFactory". This mechanism is described also in Android's online document.

http://developer.android.com/reference/javax/xml/parsers/SAXParser.html

So, I tried the following code to replace the implementation of SAXParserFactory with xerces's one.

System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");

However, this did not work, and I finally found that Android's SAXParserFactory does not support the mechanism to replace the implementation.

http://www.java2s.com/Open-Source/Android/android-core/platform-libcore/javax/xml/parsers/SAXParserFactory.java.htm

/**
 * Returns Android's implementation of {@code SAXParserFactory}. Unlike
 * other Java implementations, this method does not consult system
 * properties, property files, or the services API.
 *
 * @return a new SAXParserFactory.
 *
 * @exception FactoryConfigurationError never. Included for API
 *     compatibility with other Java implementations.
 */
public static SAXParserFactory newInstance() {
    // instantiate the class directly rather than using reflection
    return new SAXParserFactoryImpl();
}

So, I returned back to the report of Issue 9493. It says that gdata-java-client defines and uses SecureGenericXMLFactory and it intentionally disables some features that are needed to parse YouTube responses.

The actual source code lines to disable the necessary features are written in the constructor of SecureSAXParserFactory, which is an internal class of SecureGenericXMLFactory.

/* Setting the attribute
 * http://apache.org/xml/features/disallow-doctype-decl to true causes an
 * immediate exception when a DTD is encountered. Unfortunately, an XML
 * document will sometimes include a harmless DTD so we cannot ban DTDs
 * outright.
 */
try {
  factory.setFeature(
    "http://xml.org/sax/features/external-general-entities",
    false);
} catch (IllegalArgumentException e) {
  /* OK.  Not all parsers will support this attribute */
} catch (SAXNotRecognizedException e) {
  /* OK.  Not all parsers will support this attribute */
}

try {
  factory.setFeature(
    "http://xml.org/sax/features/external-parameter-entities",false);
} catch (IllegalArgumentException e) {
  /* OK.  Not all parsers will support this attribute */
} catch (SAXNotRecognizedException e) {
  /* OK.  Not all parsers will support this attribute */
}

After seeing this fact, the solution I adopted was to replace the implementation of SecureGenericXMLFactory with my own. The concrete steps were as follows.

(1) Remove the original SecureGenericXMLFactory from gdata-core-1.0.jar

cd gdata-src.java-1.46.0/gdata/java/lib
mkdir gdata-core-1.0-no-SecureGenericXMLFactory
cd gdata-core-1.0-no-SecureGenericXMLFactory
jar xf ../gdata-core-1.0.jar
rm -rf com/google/gdata/util/common/xml/parsing
jar cfm ../gdata-core-1.0-no-SecureGenericXMLFactory.jar META-INF/MANIFEST.MF com

(2) Replace the original JAR file with the new one created by the step (1) in Eclipse.

(3) Copy the original source code of SecureGenericXMLFactory to my Android project.

(4) Add an unconditional 'return' in the constructor of SecureSAXParserFactory before the code lines that disable the necessary features.

// "if (true)" was added to avoid a compilation error in Eclipse.
if (true)
{
    return;
}


The detailed report of Issue 9493 was really helpful. I want to thank the reporter.