<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Yukun&#039;s Blog &#187; Java</title>
	<atom:link href="http://www.yukun.info/blog/category/java/feed" rel="self" type="application/rss+xml" />
	<link>http://www.yukun.info</link>
	<description>難しいことは分かりやすく、簡単なことは面白く紹介</description>
	<lastBuildDate>Thu, 26 Jan 2012 03:33:59 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Java: TCP Socket Echo Server/Client サンプル</title>
		<link>http://www.yukun.info/blog/2011/02/java-tcp-socket-echo.html</link>
		<comments>http://www.yukun.info/blog/2011/02/java-tcp-socket-echo.html#comments</comments>
		<pubDate>Fri, 11 Feb 2011 22:30:33 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Network]]></category>
		<category><![CDATA[Socket]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1788</guid>
		<description><![CDATA[以下の2つのサンプルコードはローカルでTCP Socketを用いたEchoサーバ/クライアントを走らせるもの。Javaのネットワークプログラミングで基本となるクラスとメソッドの使いどころを確認しておきたくて作成。まぁ今は &#8230; <a href="http://www.yukun.info/blog/2011/02/java-tcp-socket-echo.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2011/02/java-tcp-socket-echo.html">Java: TCP Socket Echo Server/Client サンプル</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>以下の2つのサンプルコードはローカルでTCP Socketを用いたEchoサーバ/クライアントを走らせるもの。Javaのネットワークプログラミングで基本となるクラスとメソッドの使いどころを確認しておきたくて作成。まぁ今はnioがデファクトですけど。。</p>
<p><span id="more-1788"></span></p>
<h3>サーバ</h3>
<pre>
package tcpechoserver;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class Main {

    private static final int BUFSIZE = 32; // 受信バッファサイズ

    public static void main(String[] args) throws IOException {

	    int servPort = 5000;
		// サーバソケットの作成
	    ServerSocket servSock = new ServerSocket(servPort);

		int recvMsgSize; // 受信メッセージサイズ
		byte[] receiveBuf = new byte[BUFSIZE]; // 受信バッファ

		// クライアントからの接続を待ち受けるループ
		while (true) {
			Socket clntSock = servSock.accept(); // クライアントの接続を取得
			SocketAddress clientAddress = clntSock.getRemoteSocketAddress();
			System.out.println("接続中：" + clientAddress);

			InputStream in = clntSock.getInputStream();
			OutputStream out = clntSock.getOutputStream();

			while ((recvMsgSize = in.read(receiveBuf)) != -1) {
				out.write(receiveBuf, 0, recvMsgSize);
			}
			clntSock.close();
		}
		// 到達不能コード
	}
}
</pre>
<h3>クライアント</h3>
<pre>
package tcpechoclient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;

public class Main {

    public static void main(String[] args) throws IOException {
		String server = "localhost";
		int servPort = 5000;
		byte[] data = "Hello, Net world".getBytes();
		byte[] msg = new byte[data.length];

		Socket socket = new Socket(server, servPort);
		System.out.println("サーバとの接続を確立。");

		InputStream in = socket.getInputStream();
		OutputStream out = socket.getOutputStream();

		out.write(data); // サーバに文字列を送付
		System.out.println("送信：" + new String(data));

		// サーバからの返信を受信
		int totalBytesRcvd = 0;
		int bytesRcvd;
		while (totalBytesRcvd < data.length) { // 全文を受信するまでloop
			if ((bytesRcvd = in.read( // 引数は読込データ、Offset、読込データ長
					msg,
					totalBytesRcvd,
					data.length - totalBytesRcvd)) == -1) {
				throw new SocketException("接続遮断");
			}
			totalBytesRcvd += bytesRcvd;
		} // while end
		System.out.println("受信：" + new String(msg));

		socket.close();
	}
}
</pre>
<p>尚、java.io.InputStream#read(byte b[], int off, int len)の仕様は下記の通り。<br />
(忘れてたので備忘録としてメソッドのコメントより抜粋)</p>
<blockquote><p>
     * @param      b     the buffer into which the data is read.<br />
     * @param      off   the start offset in array <code>b</code><br />
     *                   at which the data is written.<br />
     * @param      len   the maximum number of bytes to read.<br />
     * @return     the total number of bytes read into the buffer, or<br />
     *             <code>-1</code> if there is no more data because the end of<br />
     *             the stream has been reached.
</p></blockquote>
<p>使い方はサーバ→クライアントの順で起動する。</p>
<h3>実行結果</h3>
<h4>サーバ側</h4>
<pre>
接続中：/127.0.0.1:53562
</pre>
<h4>クライアント側</h4>
<pre>
サーバとの接続を確立。
送信：Hello, Net world
受信：Hello, Net world
</pre>
<h3>リファレンス</h3>
<ol>
<li><a href="http://java.sun.com/javase/ja/6/docs/ja/api/java/net/Socket.html">クラス Socket</a></li>
<li><a href="http://java.sun.com/javase/ja/6/docs/ja/api/java/net/ServerSocket.html">クラス ServerSocket</a></li>
</ol>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html" rel="bookmark" title="2010年5月16日">Java: インターフェースとローカルのIPv6, IPv4アドレスの取得 &#8211; NetworkInterfaceクラス</a></li>
<li><a href="http://www.yukun.info/blog/2008/12/actionscript-air-url-socket-monitor.html" rel="bookmark" title="2008年12月24日">AIR: Webサーバ、Socketの接続状況を検知 &#8211; URLMonitor、SocketMonitorクラス</a></li>
<li><a href="http://www.yukun.info/blog/2008/09/cause-java-io-stream-corrupted-exception.html" rel="bookmark" title="2008年9月4日">java.io.StreamCorruptedExceptionが発生した原因とその解決策の一例</a></li>
<li><a href="http://www.yukun.info/blog/2008/10/java-inetaddress-getlocalhost.html" rel="bookmark" title="2008年10月30日">Java: ローカルホスト名とIPアドレスを取得 &#8211; InetAddress.getLocalHost()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/05/java-excite-translation.html" rel="bookmark" title="2008年5月16日">JavaプログラムからExcite翻訳を利用</a></li>
</ul>
<p><!-- Similar Posts took 17.228 ms --></p>
<p><a href="http://www.yukun.info/blog/2011/02/java-tcp-socket-echo.html">Java: TCP Socket Echo Server/Client サンプル</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2011/02/java-tcp-socket-echo.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: インターフェースとローカルのIPv6, IPv4アドレスの取得 &#8211; NetworkInterfaceクラス</title>
		<link>http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html</link>
		<comments>http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html#comments</comments>
		<pubDate>Sun, 16 May 2010 10:30:59 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Network]]></category>
		<category><![CDATA[Socket]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1561</guid>
		<description><![CDATA[下記のコードはネットワークインターフェース情報取得し、IPv6とIPv4のアドレスを取得、表示するサンプルコードです。 ソースコード import java.net.Inet4Address; import java.n &#8230; <a href="http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html">Java: インターフェースとローカルのIPv6, IPv4アドレスの取得 &#8211; NetworkInterfaceクラス</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>下記のコードはネットワークインターフェース情報取得し、IPv6とIPv4のアドレスを取得、表示するサンプルコードです。</p>
<h3>ソースコード</h3>
<pre>
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;

/**
 * ネットワークインターフェースの取得
 */
public class InetAddressesInfo {
  private HashMap&lt;NetworkInterface, ArrayList&lt;InetAddress&gt;&gt; interfaceMap;

  public InetAddressesInfo() {
    interfaceMap = new HashMap&lt;NetworkInterface, ArrayList&lt;InetAddress&gt;&gt;();
  }

  public void getInterfaces() {
    interfaceMap.clear();
    try {
      Enumeration&lt;NetworkInterface&gt; interfaceList = NetworkInterface.getNetworkInterfaces();
      if (interfaceList == null) {
        System.out.println(&quot;Message: No interfaces found&quot;);
      } else {
        while (interfaceList.hasMoreElements()) {
          NetworkInterface iface = interfaceList.nextElement();
          Enumeration&lt;InetAddress&gt; addrList = iface.getInetAddresses();
          if (!addrList.hasMoreElements()) continue;
          ArrayList&lt;InetAddress&gt; iaddress = new ArrayList&lt;InetAddress&gt;();
          while (addrList.hasMoreElements())
            iaddress.add(addrList.nextElement());
          interfaceMap.put(iface, iaddress);
        }
      }
    } catch (SocketException se) {
      System.out.println(&quot;Error getting network interfaces: &quot; + se.getMessage());
    }
  }

  public void show() {
    for (NetworkInterface n : interfaceMap.keySet()) {
      System.out.println(&quot;Interface &quot; + n.getName() + &quot;: &quot;);
      for (InetAddress a : interfaceMap.get(n)) {
        System.out.print(&quot;\tAddress &quot; + ((a instanceof Inet4Address ? &quot;(IPv4)&quot;
            : (a instanceof Inet6Address ? &quot;(IPv6)&quot; : &quot;(?)&quot;))));
        System.out.println(&quot;: &quot; + a.getHostAddress());
      }
    }
  }

  public HashMap&lt;NetworkInterface, ArrayList&lt;InetAddress&gt;&gt; getInterfaceMap() {
    return interfaceMap;
  }

  public void setInterfaceMap(
      HashMap&lt;NetworkInterface, ArrayList&lt;InetAddress&gt;&gt; interfaceMap) {
    this.interfaceMap = interfaceMap;
  }

  public static void main(String[] args) {
    InetAddressesInfo i =  new InetAddressesInfo();
    i.getInterfaces();
    i.show();
  }

}
</pre>
<h3>実行結果</h3>
<pre>
Interface lo:
	Address (IPv6): 0:0:0:0:0:0:0:1
	Address (IPv4): 127.0.0.1
Interface net4:
	Address (IPv6): fe80:0:0:0:0:5efe:c0a8:10a%12
Interface net5:
	Address (IPv6): 2001:0:4137:9e76:8ae:1cf7:3f57:fef5
	Address (IPv6): fe80:0:0:0:8ae:1cf7:3f57:fef5%13
Interface eth3:
	Address (IPv6): 2001:c90:33d:21d4:919c:836b:2d1a:cf33
	Address (IPv6): 2001:c90:33d:21d4:8856:aef1:d0bd:db64
	Address (IPv6): fe80:0:0:0:919c:836b:2d1a:cf33%11
	Address (IPv4): 192.168.1.10
</pre>
<h3>ドキュメント</h3>
<p>・<a href="http://java.sun.com/javase/ja/6/docs/ja/api/java/net/NetworkInterface.html" target="_blank">NetworkInterface (Java Platform SE 6)</a></p>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2011/02/java-tcp-socket-echo.html" rel="bookmark" title="2011年2月12日">Java: TCP Socket Echo Server/Client サンプル</a></li>
<li><a href="http://www.yukun.info/blog/2008/10/java-inetaddress-getlocalhost.html" rel="bookmark" title="2008年10月30日">Java: ローカルホスト名とIPアドレスを取得 &#8211; InetAddress.getLocalHost()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/03/java-ngram.html" rel="bookmark" title="2008年3月7日">検索エンジンを実装 (1)転置インデックス作成</a></li>
<li><a href="http://www.yukun.info/blog/2008/05/java-excite-translation.html" rel="bookmark" title="2008年5月16日">JavaプログラムからExcite翻訳を利用</a></li>
<li><a href="http://www.yukun.info/blog/2008/12/actionscript-air-url-socket-monitor.html" rel="bookmark" title="2008年12月24日">AIR: Webサーバ、Socketの接続状況を検知 &#8211; URLMonitor、SocketMonitorクラス</a></li>
</ul>
<p><!-- Similar Posts took 11.502 ms --></p>
<p><a href="http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html">Java: インターフェースとローカルのIPv6, IPv4アドレスの取得 &#8211; NetworkInterfaceクラス</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: ServletからJSPへリクエストをフォワード</title>
		<link>http://www.yukun.info/blog/2010/03/java-servlet-jsp-request-forward.html</link>
		<comments>http://www.yukun.info/blog/2010/03/java-servlet-jsp-request-forward.html#comments</comments>
		<pubDate>Thu, 25 Mar 2010 15:00:01 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[Servlet]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1472</guid>
		<description><![CDATA[目的 Servletで処理した結果をJSPファイルに転送し、HTMLを生成する。これによって、MVCモデルにおけるViewの分離ができる。 方法 protected void doGet(HttpServletReque &#8230; <a href="http://www.yukun.info/blog/2010/03/java-servlet-jsp-request-forward.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2010/03/java-servlet-jsp-request-forward.html">Java: ServletからJSPへリクエストをフォワード</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<h3>目的</h3>
<p>Servletで処理した結果をJSPファイルに転送し、HTMLを生成する。これによって、MVCモデルにおけるViewの分離ができる。</p>
<h3>方法</h3>
<pre>
protected void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {
	ArrayList&lt;String[]&gt; table = new ArrayList&lt;String[]&gt;(); // 転送データ
＜中略＞
	req.setAttribute(&quot;table&quot;, table);
	req.getRequestDispatcher(&quot;jsp/view.jsp&quot;).forward(req, res);
</pre>
<p>上記のServletコード上のtableという変数をview.jspに渡したす場合、HttpServletRequest #setAttributeで変数を登録し、getRequestDispatcherとforwardでリクエストをフォワードする。</p>
<p>JSP側で登録した変数を取り出すには、下記のコードを用いる。</p>
<pre>
&lt;% ArrayList&lt;String[]&gt; table = (ArrayList&lt;String[]&gt;)request.getAttribute(&quot;table&quot;); %&gt;
</pre>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2010/03/java-no-suitable-driver-found.html" rel="bookmark" title="2010年3月24日">Java, Servlet: No suitable driver found for &#8220;～&#8221; の原因と解決法</a></li>
<li><a href="http://www.yukun.info/blog/2009/02/java-jsp-gregoriancalendar-period.html" rel="bookmark" title="2009年2月23日">Java, JSP: 現在時刻が指定期間内か判定する &#8211; GregorianCalendar#before、after</a></li>
<li><a href="http://www.yukun.info/blog/2009/03/java-observe-event-model-view.html" rel="bookmark" title="2009年3月17日">Java: イベント駆動によるModelとViewの分離 &#8211; Observer パターン</a></li>
<li><a href="http://www.yukun.info/blog/2008/10/android-integer-to-binary-string.html" rel="bookmark" title="2008年10月29日">Android: 10進数→2進数変換アプリ</a></li>
<li><a href="http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html" rel="bookmark" title="2010年5月16日">Java: インターフェースとローカルのIPv6, IPv4アドレスの取得 &#8211; NetworkInterfaceクラス</a></li>
</ul>
<p><!-- Similar Posts took 8.704 ms --></p>
<p><a href="http://www.yukun.info/blog/2010/03/java-servlet-jsp-request-forward.html">Java: ServletからJSPへリクエストをフォワード</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2010/03/java-servlet-jsp-request-forward.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: 形態素解析Senをインストール(Windows編)</title>
		<link>http://www.yukun.info/blog/2010/03/java-install-sen-windows.html</link>
		<comments>http://www.yukun.info/blog/2010/03/java-install-sen-windows.html#comments</comments>
		<pubDate>Thu, 25 Mar 2010 11:00:02 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Sen]]></category>
		<category><![CDATA[Setting]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1470</guid>
		<description><![CDATA[ダウンロードするソフト 1.ActivePerl(ActivePerl, Download Perl for Windows, Mac, Linux, AIX, HP-UX &#38; Solaris) 2.Apache &#8230; <a href="http://www.yukun.info/blog/2010/03/java-install-sen-windows.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2010/03/java-install-sen-windows.html">Java: 形態素解析Senをインストール(Windows編)</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<h3>ダウンロードするソフト</h3>
<p>1.ActivePerl(<a href="http://www.activestate.com/activeperl/">ActivePerl, Download Perl for Windows, Mac, Linux, AIX, HP-UX &amp; Solaris</a>)<br />
2.Apache Ant(<a href="http://ant.apache.org/bindownload.cgi">Apache Ant &#8211; Binary Distributions</a>)<br />
3.Sen(<a href="http://java.net/projects/sen">sen: ドキュメント &amp; ファイル: release</a>)</p>
<p><span id="more-1470"></span></p>
<p>ActivePerlはインストーラーに従いインストールする。<br />
ダウンロードしたAntとSenはC:\work以下に解凍し、フォルダ名をそれぞれapache-ant、senとリネームする。</p>
<h3>環境変数の設定</h3>
<p>PATH(追加)	C:\work\apache-ant\bin;<br />
ANT_HOME	C:\work\apache-ant<br />
SEN_HOME	C:\work\sen<br />
JAVA_HOME	C:\Sun\SDK\jdk<br />
この後、上記の環境変数が適応されているか下記のコマンドを用いて確認する。</p>
<pre>
C:\>echo %ANT_HOME%
C:\work\apache-ant (←OK、パスが適応されている)
</pre>
<p>適応されていなければ再起動する。</p>
<h3>辞書のインストール方法</h3>
<p>カレントディレクトリをdicに設定後、辞書をインストールする。</p>
<pre>
C:\>cd work/sen/dic (←カレントディレクトリを移動)
C:\work\sen\dic>ant -Dperl.bin=C:\Perl\bin\perl.exe (←辞書のインストール)
Buildfile: C:\work\sen\dic\build.xml
＜中略＞
BUILD SUCCESSFUL
Total time: 1 minute 2 seconds
C:\work\sen\dic>
</pre>
<h3>動作確認</h3>
<p>%SEN_HOME%\sen.batをダブルクリックする。</p>
<pre>
C:\work\sen\bin>rem set classpath
C:\work\sen\bin>SET CLASSPATH=C:\work\sen\lib\sen.jar
C:\work\sen\bin>SET CLASSPATH=C:\work\sen\lib\sen.jar;C:\work\sen\lib\commons-logging.jar
done.
Please input Japanese sentence:
2010/03/25 0:29:44 net.java.sen.Dictionary <init>
情報: token file = C:\work\sen\dic/token.sen
2010/03/25 0:29:44 net.java.sen.Dictionary <init>
情報: time to load posInfo file = 16[ms]
2010/03/25 0:29:44 net.java.sen.Dictionary <init>
情報: double array trie dictionary = C:\work\sen\dic/da.sen
2010/03/25 0:29:44 net.java.sen.util.DoubleArrayTrie load
情報: loading double array trie dict = C:\work\sen\dic/da.sen
2010/03/25 0:29:45 net.java.sen.util.DoubleArrayTrie load
情報: loaded time = 0.453[ms]
2010/03/25 0:29:45 net.java.sen.Dictionary <init>
情報: pos info file = C:\work\sen\dic/posInfo.sen
2010/03/25 0:29:45 net.java.sen.Dictionary <init>
情報: time to load pos info file = 0[ms]
2010/03/25 0:29:45 net.java.sen.Tokenizer loadConnectCost
情報: connection file = C:\work\sen\dic\matrix.sen
2010/03/25 0:29:45 net.java.sen.Tokenizer loadConnectCost
情報: time to load connect cost file = 141[ms]
hello
hello   (hello) 未知語(0,5,5)   null    null
こんにちは
こんにちは      (こんにちは)    感動詞(0,5,5)   コンニチハ      コンニチワ
</pre>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2010/04/setup-eclipse-64bit-android.html" rel="bookmark" title="2010年4月25日">Windows7 64bitにEclipseでAndroid開発環境をセットアップ</a></li>
<li><a href="http://www.yukun.info/blog/2008/01/cygwin-cron.html" rel="bookmark" title="2008年1月8日">Cygwinでcronをインストール</a></li>
<li><a href="http://www.yukun.info/blog/2009/02/netbeans-subversion-import-error.html" rel="bookmark" title="2009年2月12日">NetBeans から Subversion でコミットをする際のエラーの解決法の一例</a></li>
<li><a href="http://www.yukun.info/blog/2008/06/install-lxml.html" rel="bookmark" title="2008年6月13日">Python: lxmlのインストール方法</a></li>
<li><a href="http://www.yukun.info/blog/2011/02/vmware-player-centos.html" rel="bookmark" title="2011年2月23日">VMware PlayerでCentOSをインストール</a></li>
</ul>
<p><!-- Similar Posts took 11.502 ms --></p>
<p><a href="http://www.yukun.info/blog/2010/03/java-install-sen-windows.html">Java: 形態素解析Senをインストール(Windows編)</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2010/03/java-install-sen-windows.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Java, Servlet: No suitable driver found for &#8220;～&#8221; の原因と解決法</title>
		<link>http://www.yukun.info/blog/2010/03/java-no-suitable-driver-found.html</link>
		<comments>http://www.yukun.info/blog/2010/03/java-no-suitable-driver-found.html#comments</comments>
		<pubDate>Tue, 23 Mar 2010 15:00:32 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Exception]]></category>
		<category><![CDATA[Servlet]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1467</guid>
		<description><![CDATA[事象 &#8211; NullPointerException on java.sql.Connection JDBCを用いてServletからMySQLのテーブルへアクセスする過程で、DriverManager.get &#8230; <a href="http://www.yukun.info/blog/2010/03/java-no-suitable-driver-found.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2010/03/java-no-suitable-driver-found.html">Java, Servlet: No suitable driver found for &#8220;～&#8221; の原因と解決法</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<h3>事象 &#8211; NullPointerException on java.sql.Connection</h3>
<p>JDBCを用いてServletからMySQLのテーブルへアクセスする過程で、DriverManager.getConnectionメソッドの呼び出しの後、NullPointerExceptionが送出された(アプリケーション・サーバーはTomcat)。</p>
<pre>
＜前略＞
Connection conn = null;
    try {
      conn = DriverManager.getConnection(URL, USER, PASS);
      Statement stmt = conn.createStatement();
      ResultSet rs = stmt.executeQuery(&quot;&lt;SQL文&gt;&quot;);
＜後略＞
</pre>
<p><a href="http://www.yukun.info/wp-content/uploads/tomcat_error_nullpointer-e1269499672856.png"><img src="http://www.yukun.info/wp-content/uploads/tomcat_error_nullpointer-e1269499672856.png" alt="tomcat_error_nullpointer" title="tomcat_error_nullpointer" width="400" height="304" class="size-full wp-image-1471" /></a></p>
<h3>原因 &#8211; No suitable driver found for &#8220;～&#8221;</h3>
<p>デバックトレースを行ったところ、No suitable driver found for &#8220;～&#8221;というメッセージが出力されていた。JDBC Driver のクラスパスを設定していなかった為、今回のエラーが発生した。</p>
<h3>対策 &#8211; JDBC Driverのクラスパス設定</h3>
<p>JDBC Driver ファイル(.jar)をクラスパスに追加する。Eclipse上での設定方法は「実行」→「実行の構成」から「クラスパス」タブ内の「ユーザー・エントリー」を選択、「外部JARの追加」ボタンから、Driverを設定する。</p>
<h3>雑感</h3>
<p>ありがちー、なミスをしてしまったー。</p>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/09/cause-java-io-stream-corrupted-exception.html" rel="bookmark" title="2008年9月4日">java.io.StreamCorruptedExceptionが発生した原因とその解決策の一例</a></li>
<li><a href="http://www.yukun.info/blog/2008/05/out-of-memory-error.html" rel="bookmark" title="2008年5月8日">java.lang.OutOfMemoryErrorが発生する原因とその解決法の一例</a></li>
<li><a href="http://www.yukun.info/blog/2010/03/java-servlet-jsp-request-forward.html" rel="bookmark" title="2010年3月26日">Java: ServletからJSPへリクエストをフォワード</a></li>
<li><a href="http://www.yukun.info/blog/2008/01/amateras-uml.html" rel="bookmark" title="2008年1月4日">JavaのソースコードからUMLのクラス図を作成</a></li>
<li><a href="http://www.yukun.info/blog/2008/03/diff-java-ruby-string.html" rel="bookmark" title="2008年3月4日">JavaとRubyで文字列の終端の扱いの違い</a></li>
</ul>
<p><!-- Similar Posts took 8.905 ms --></p>
<p><a href="http://www.yukun.info/blog/2010/03/java-no-suitable-driver-found.html">Java, Servlet: No suitable driver found for &#8220;～&#8221; の原因と解決法</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2010/03/java-no-suitable-driver-found.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: OR論理演算子の評価条件</title>
		<link>http://www.yukun.info/blog/2009/05/java-or-operand.html</link>
		<comments>http://www.yukun.info/blog/2009/05/java-or-operand.html#comments</comments>
		<pubDate>Sun, 24 May 2009 13:00:06 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1437</guid>
		<description><![CDATA[以前、OR演算の2つのオペランドが両方評価されるか否かがあやふやだったので以下のコードを以て改めて確認してみます。 public class Sample1 { public static void main(Strin &#8230; <a href="http://www.yukun.info/blog/2009/05/java-or-operand.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2009/05/java-or-operand.html">Java: OR論理演算子の評価条件</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>以前、OR演算の2つのオペランドが両方評価されるか否かがあやふやだったので以下のコードを以て改めて確認してみます。</p>
<pre>
public class Sample1 {
  public static void main(String[] args) {
    int i = 5, j = 10, k =15;
    if ((i++ < j) | (k-- > j))
      System.out.println("values of i: " + i + " values of k: " + k);
    if ((i < j) || (--k > j))
      System.out.println("values of k: " + k);
  }
}
</pre>
<p>実行結果は</p>
<pre>
values of i: 6 values of k: 14
values of k: 14
</pre>
<p>となります。<br />
1つめのif文で使われている演算子はビット論理OR演算子で左右の<strong>両オペランドを評価</strong>します。よって式i++とk&#8211;が評価されているため結果はvalues of i: 6 values of k: 14となります。</p>
<p>2つめのif文で使われているのは短絡論理OR演算子で、評価順序は||の<em>左側のオペランドを先ず評価し</em>、それがtrueなら<em>右側は評価せず</em>(ORは片方が真ならもう片方の結果にかかわらず真ですから)、<em>falseなら評価</em>します。よって、if ((i < j) || (--k > j))ではi < jがtrueとなるため--k > jは評価されずkはデクリメントされません。よってkの値は変わらず、上記のような実行結果となります。</p>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/06/java-subtraction.html" rel="bookmark" title="2008年6月4日">検索エンジンを実装 (6)NOT演算</a></li>
<li><a href="http://www.yukun.info/blog/2008/05/java-union.html" rel="bookmark" title="2008年5月27日">検索エンジンを実装 (5)OR演算</a></li>
<li><a href="http://www.yukun.info/blog/2008/05/java-intersection.html" rel="bookmark" title="2008年5月20日">検索エンジンを実装 (4)AND演算</a></li>
<li><a href="http://www.yukun.info/blog/2010/03/java-install-sen-windows.html" rel="bookmark" title="2010年3月25日">Java: 形態素解析Senをインストール(Windows編)</a></li>
<li><a href="http://www.yukun.info/blog/2008/05/java-strip.html" rel="bookmark" title="2008年5月29日">Java: 文字列の先頭・末尾の文字を削除するstrip()メソッド</a></li>
</ul>
<p><!-- Similar Posts took 7.936 ms --></p>
<p><a href="http://www.yukun.info/blog/2009/05/java-or-operand.html">Java: OR論理演算子の評価条件</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2009/05/java-or-operand.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: イベント駆動によるModelとViewの分離 &#8211; Observer パターン</title>
		<link>http://www.yukun.info/blog/2009/03/java-observe-event-model-view.html</link>
		<comments>http://www.yukun.info/blog/2009/03/java-observe-event-model-view.html#comments</comments>
		<pubDate>Tue, 17 Mar 2009 11:30:38 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Time]]></category>
		<category><![CDATA[UML]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1401</guid>
		<description><![CDATA[よくGUIやWebアプリの簡単なサンプルソースなどは、UIとアプリケーションのロジックが同じクラスまたはメソッドに書かれている場合が多いです。それはそのサンプルがある特定の機能や関数の紹介の為に簡潔に書いているのですが、 &#8230; <a href="http://www.yukun.info/blog/2009/03/java-observe-event-model-view.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2009/03/java-observe-event-model-view.html">Java: イベント駆動によるModelとViewの分離 &#8211; Observer パターン</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>よくGUIやWebアプリの簡単なサンプルソースなどは、UIとアプリケーションのロジックが同じクラスまたはメソッドに書かれている場合が多いです。それはそのサンプルがある特定の機能や関数の紹介の為に簡潔に書いているのですが、仮にいざそのソースを元にアプリを作りこんで機能の追加を行っていくとUIとアプリのロジックは分離したほうが保守・拡張と共に行いやすいです。</p>
<p>下記のプログラムは1秒毎に数値をカウントし、それを2進数と10進数でGUI上のラベルに出力する機能をモデルとビューに分けています。すなわち、数値のカウントをするモデルと数値をUIに表示するビューに。（いくつかの言語ではGUIの部品として<a href="http://www.yukun.info/blog/2008/02/csharp-timer.html">タイマーがある</a>ようですが。。）</p>
<h2>実行結果</h2>
<p><a href="http://www.yukun.info/wp-content/uploads/count_timer01.png"><img src="http://www.yukun.info/wp-content/uploads/count_timer01.png" alt="count_timer01" title="count_timer01" width="125" height="69" class="size-full wp-image-1485" /></a></p>
<h2>クラス図</h2>
<p><a href="http://www.yukun.info/wp-content/uploads/countmodel_view_class.png"><img src="http://www.yukun.info/wp-content/uploads/countmodel_view_class-e1271583675800.png" alt="countmodel_view_class" title="countmodel_view_class" width="400" height="236" class="size-full wp-image-1486" /></a></p>
<p>インスタンスの生成はコンストラクタで行うのがいいのですが、はしょっています。さて、これまでに何らかのフレームワークを使っていた方には上クラス図はMVCの説明図として見慣れているかもしれません。今回ModelとViewを繋ぐControllerの役割はCountListenerが担っています（下記コードではCountChangeEvent経由でModelインスタンスを渡すのみですが）。</p>
<h3>処理手順</h3>
<p>ビュー側で自身のインスタンスをモデルに登録し（モデル.addCountListener(ビュー)）、モデルのデータが更新された場合、モデル→ビューへイベントを送出。イベント内部にモデルのデータがあり、そのデータでビューがUIを更新します。イベントの発生順序等は下図のシーケンス図のようになります。</p>
<h2>シーケンス図</h2>
<p><a href="http://www.yukun.info/wp-content/uploads/countmodel_view_sequence.png"><img src="http://www.yukun.info/wp-content/uploads/countmodel_view_sequence.png" alt="countmodel_view_sequence" title="countmodel_view_sequence" width="372" height="312" class="size-full wp-image-1487" /></a></p>
<h3>無限ループに注意</h3>
<p>ビューを更新するイベントリスナーのメソッド（ここではcountChanged()）で再度モデルのプロパティ変更メソッド（ここではsetCount()）を用いると、再度イベント通知処理（notifyToListeners()）が発生することで、無限ループになるので注意が必要です。</p>
<h3>ビューの追加手順</h3>
<p>ビューを追加する際の手順は、ビューのインスタンスをモデルのリスナーに登録し（addCountListener()）、ビュー自身がリスナーのメソッドを実装することで（countChanged()）、モデルからのイベントを受け取ることが出来ます。</p>
<p>そういえば最近はIDEの方でバインド設定したり、ObservableList等があるのであまり意識することがなくなってきたなぁ。</p>
<h2>ソースコード</h2>
<pre>
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

class CountView extends JFrame implements CountListener{

	private final JLabel binaryLabel = new JLabel("0");
	private final JLabel decimalLabel = new JLabel("0");
	private CountModel cModel = new CountModel(0);

	public static void main(String[] args) {
		new CountView();
	}

	public CountView() {
		super("Counter");
		Container c = getContentPane();
		c.setLayout(new GridLayout(2, 2));
		c.add(new JLabel(" 2進数:"));
		c.add(binaryLabel);
		c.add(new JLabel("10進数:"));
		c.add(decimalLabel);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		cModel.addCountListener(this); // ModelにViewを登録

		pack();
		setVisible(true);
	}

	public void countChanged(CountChangeEvent e) {
		if (e.getSource() == cModel) {
			binaryLabel.setText(Integer.toString(cModel.getCount(), 2));
			decimalLabel.setText(Integer.toString(cModel.getCount(), 10));
		}
	}
}
</pre>
<pre>
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * カウントするModel
 */
public class CountModel {

	private int count;
	private final List&lt;CountListener&gt; listeners = new ArrayList&lt;CountListener&gt;();
	private Timer t = new Timer(&quot;Count Timer&quot;, false);

	CountModel(int i) {
		count = i;
		t.scheduleAtFixedRate(new CountTime(), 0, 1000);
	}

	// Viewを登録
	public void addCountListener(CountListener listener) {
		listeners.add(listener);
	}

	public int getCount() {
		return count;
	}

	public void setCount(int i) {
		count = i;
		notifyToListeners();
	}

	// Viewへの通知
	private void notifyToListeners() {
		for (CountListener listener : listeners) {
			listener.countChanged(new CountChangeEvent(this));
		}
	}

	class CountTime extends TimerTask {
		@Override
		public void run() {
			setCount(getCount() + 1);
		}
	}
}
</pre>
<pre>
/**
 * View側で実装する(Model側から呼び出し)
 */
public interface CountListener {
	public void countChanged(CountChangeEvent e);
}

/**
 * 通知内容を表すイベント(Modelが生成しViewが受け取る)
 */
public class CountChangeEvent {
	private final CountModel source;

	public CountChangeEvent(CountModel count) {
		this.source = count;
	}

	public CountModel getSource() {
		return source;
	}
}
</pre>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/10/android-integer-to-binary-string.html" rel="bookmark" title="2008年10月29日">Android: 10進数→2進数変換アプリ</a></li>
<li><a href="http://www.yukun.info/blog/2008/02/csharp-timer.html" rel="bookmark" title="2008年2月24日">C#でキッチンタイマーを作ろう</a></li>
<li><a href="http://www.yukun.info/blog/2008/11/actionscript-flash-load-server-image-file.html" rel="bookmark" title="2008年11月21日">ActionScript: 画像ファイルをダウンロードして表示 &#8211; Loaderクラス</a></li>
<li><a href="http://www.yukun.info/blog/2009/03/java-design-pattern-simple-factory.html" rel="bookmark" title="2009年3月15日">Java, デザインパターン: Simple Factory &#8211; インスタンスの生成方法を任せる</a></li>
<li><a href="http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html" rel="bookmark" title="2010年5月16日">Java: インターフェースとローカルのIPv6, IPv4アドレスの取得 &#8211; NetworkInterfaceクラス</a></li>
</ul>
<p><!-- Similar Posts took 12.857 ms --></p>
<p><a href="http://www.yukun.info/blog/2009/03/java-observe-event-model-view.html">Java: イベント駆動によるModelとViewの分離 &#8211; Observer パターン</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2009/03/java-observe-event-model-view.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java, デザインパターン: Simple Factory &#8211; インスタンスの生成方法を任せる</title>
		<link>http://www.yukun.info/blog/2009/03/java-design-pattern-simple-factory.html</link>
		<comments>http://www.yukun.info/blog/2009/03/java-design-pattern-simple-factory.html#comments</comments>
		<pubDate>Sun, 15 Mar 2009 09:10:00 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[UML]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1338</guid>
		<description><![CDATA[以前デザインパターンの理解の確認がてら簡単なコードを書いていたので投稿してみます。リファクタリングの前後を省いているので初見ではパターンのメリットと適応基準が見えにくく、またサンプルのテーマ設定が良くなかったのでイマイチ &#8230; <a href="http://www.yukun.info/blog/2009/03/java-design-pattern-simple-factory.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2009/03/java-design-pattern-simple-factory.html">Java, デザインパターン: Simple Factory &#8211; インスタンスの生成方法を任せる</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>以前デザインパターンの理解の確認がてら簡単なコードを書いていたので投稿してみます。リファクタリングの前後を省いているので初見ではパターンのメリットと適応基準が見えにくく、またサンプルのテーマ設定が良くなかったのでイマイチ説明し難い（反省）。今回のようなToyコードみたいなのはたまに書くのですが、Blog記事としてまとめるのが手間で大抵HDDの片隅に眠ってしまうのですが、今後はとりあえず上げていこうかと思います。説明などは隙をみて書き足していく感じでまず投稿、みたいな。ただ、そればっかりだと後で自分が読んだときに分からなくなるので、ほどほどにしよう。</p>
<h2>クラス図</h2>
<p><a href="http://www.yukun.info/wp-content/uploads/simple_factory_classes.png"><img src="http://www.yukun.info/wp-content/uploads/simple_factory_classes-e1271583536302.png" alt="simple_factory_classes" title="simple_factory_classes" width="400" height="196" class="size-full wp-image-1483" /></a></p>
<p>文字列の分割プログラム。</p>
<p>入力: クラス名＋＜区切り文字＞＋メソッド名の文字列<br />
出力: その文字列の分割結果が格納されたインスタンス（Namerクラス）。</p>
<p>文字列の形式が&#8221;＜クラス名＞#＜メソッド名＞&#8221;か&#8221;＜クラス名＞.＜メソッド名＞&#8221;によって、すなわち区切り文字によって分割処理のメソッドの内容が変わるので、その違いを派生クラスでオーバーライドして定義したメソッドで吸収しようというもの。</p>
<p>これによる利点はMain側が分割対象の文字列の形式を意識しなくてよいこと。単にNameFactory#getNamer()に渡すだけ。文字列の形式が2つの内のどちらで、どのクラスに処理を任せるかの処理はgetNamer()が行う。これによって、仮に文字列の形式を増やす場合に修正するのはgetNamer()のifブロック、追加するのは新しい派生クラス。</p>
<h2>ソースコード</h2>
<pre>
public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        NameFactory nameFactory = new NameFactory();
        Namer namer;
        namer = nameFactory.getNamer("String#indexOf()");
        printName(namer);
        namer = nameFactory.getNamer("ArrayList.get()");
        printName(namer);
        namer = nameFactory.getNamer("Thread#run()");
        printName(namer);
    }

    private void printName(Namer namer) {
        System.out.println("Class  Name: " + namer.className);
        System.out.println("Method Name: " + namer.methodName);
    }

}

public class NameFactory {
    // 区切り文字の種類によって、処理する派生クラスを決める
    public Namer getNamer(String input) {
        if (input.indexOf(".") > 0)
            return new PeriodNamer(input);
        else if (input.indexOf("#") > 0)
            return new SharpNamer(input);
        return null;
    }
}

public class Namer {

    protected String className;
    protected String methodName;

    public String getClassName() {
        return className;
    }

    public String getMethodName() {
        return methodName;
    }
}

public class SharpNamer extends Namer {
    // 「#」で名前を区切る
    public SharpNamer(String str) {
        int i = str.lastIndexOf("#");
        if (i > 0) {
            className = str.substring(0, i); // (beginIndex, endIndex)
            methodName = str.substring(i + 1); // (beginIndex)
        } else {
            className = "";
            methodName = str;
        }
    }
}

public class PeriodNamer extends Namer {
    // 「.」で名前を区切る
    public PeriodNamer(String str) {
        int i = str.lastIndexOf(".");
        if (i > 0) {
            className = str.substring(0, i); // (beginIndex, endIndex)
            methodName = str.substring(i + 1); // (beginIndex)
        } else {
            className = "";
            methodName = str;
        }
    }
}
</pre>
<h2>実行結果</h2>
<pre>
Class  Name: String
Method Name: indexOf()
Class  Name: ArrayList
Method Name: get()
Class  Name: Thread
Method Name: run()
</pre>
<p>書いた後ふと考えたのですが、これ100形式だと100派生クラスで、if-elseブロックもえらいことになるなぁ。こういう時、現時点では思考停止してしまうので、今月の課題。</p>
<p>今後はなるべく制作中のアプリの中での問題かそれに関わるもの、絡められるものを取り上げていきたい。</p>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2009/03/java-observe-event-model-view.html" rel="bookmark" title="2009年3月17日">Java: イベント駆動によるModelとViewの分離 &#8211; Observer パターン</a></li>
<li><a href="http://www.yukun.info/blog/2008/01/amateras-uml.html" rel="bookmark" title="2008年1月4日">JavaのソースコードからUMLのクラス図を作成</a></li>
<li><a href="http://www.yukun.info/blog/2011/02/java-tcp-socket-echo.html" rel="bookmark" title="2011年2月12日">Java: TCP Socket Echo Server/Client サンプル</a></li>
<li><a href="http://www.yukun.info/blog/2008/11/java-user-system-in-inputstream-read.html" rel="bookmark" title="2008年11月2日">Java: ユーザからの(標準)入力を取得 &#8211; System.inとInputStreamReaderクラス</a></li>
<li><a href="http://www.yukun.info/blog/2008/11/implement-chatterbot-append-suffix.html" rel="bookmark" title="2008年11月3日">人工無脳を作ってみる (1)入力文の末尾に文字列を追加</a></li>
</ul>
<p><!-- Similar Posts took 14.150 ms --></p>
<p><a href="http://www.yukun.info/blog/2009/03/java-design-pattern-simple-factory.html">Java, デザインパターン: Simple Factory &#8211; インスタンスの生成方法を任せる</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2009/03/java-design-pattern-simple-factory.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java, JSP: 現在時刻が指定期間内か判定する &#8211; GregorianCalendar#before、after</title>
		<link>http://www.yukun.info/blog/2009/02/java-jsp-gregoriancalendar-period.html</link>
		<comments>http://www.yukun.info/blog/2009/02/java-jsp-gregoriancalendar-period.html#comments</comments>
		<pubDate>Mon, 23 Feb 2009 12:10:09 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Date]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JSP]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1390</guid>
		<description><![CDATA[日時を扱うクラスはDateとGregorianCalendarがありますが、Sunは後者を推奨しているようです。実際GregorianCalendarのほうが扱いやすいです。下のサンプルは、現在時刻が指定した期間内か否か &#8230; <a href="http://www.yukun.info/blog/2009/02/java-jsp-gregoriancalendar-period.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2009/02/java-jsp-gregoriancalendar-period.html">Java, JSP: 現在時刻が指定期間内か判定する &#8211; GregorianCalendar#before、after</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>日時を扱うクラスはDateとGregorianCalendarがありますが、Sunは後者を推奨しているようです。実際GregorianCalendarのほうが扱いやすいです。下のサンプルは、現在時刻が指定した期間内か否かを判定するものです。</p>
<h2>ソースコード</h2>
<pre>
&lt;%@page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;%@page import=&quot;java.util.*&quot; %&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
   &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
  &lt;%!
    final int MONTH_OFFSET = 1;

    String showTime(Calendar cal) {
      String str;
      str = cal.get(Calendar.YEAR) + &quot;/&quot;
        + (cal.get(Calendar.MONTH) + MONTH_OFFSET)  + &quot;/&quot;
        + cal.get(Calendar.DATE) + &quot; &quot;
        + cal.get(Calendar.HOUR) + &quot;:&quot;
        + cal.get(Calendar.MINUTE);
      return str;
    }

    boolean isPeriod(Calendar start, Calendar end) {
      Calendar cur = Calendar.getInstance();
      return cur.after(start) &amp;&amp; cur.before(end);
    }
  %&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt;JSP Date Comparison&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;JSP Date Comparison&lt;/h1&gt;
    &lt;%
      // (year, month, date, hour, minute) monthの範囲は0-11で1月は0
      Calendar startTime = new GregorianCalendar(2009, 2 - MONTH_OFFSET, 23, 21, 0);
      Calendar endTime = new GregorianCalendar(2009, 2 - MONTH_OFFSET, 23, 21, 10);

      out.println(&quot;開始時刻: &quot; + showTime(startTime) + &quot;&lt;br /&gt;&quot;);
      out.println(&quot;終了時刻: &quot; + showTime(endTime) + &quot;&lt;br /&gt;&quot;);

      if (isPeriod(startTime, endTime)) {
        out.println(&quot;現時刻は指定期間「内」&quot;);
      } else {
        out.println(&quot;現時刻は指定期間「外」&quot;);
      }
    %&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>日時の比較はGregorianCalendar#after、beforeメソッド以外にint compareTo(Calendar cal)等もあります。<br />
実際に使う際、期間を指定するGregorianCalendarのコンストラクタの引数データは他の入力から受け取るようにします。</p>
<h2>実行結果例</h2>
<p>本日の21:05に計ると…</p>
<pre>
JSP Date Comparison
開始時刻: 2009/2/23 9:0
終了時刻: 2009/2/23 9:10
現時刻は指定期間「内」
</pre>
<h2>追記: SimpleDateFormatによる出力の整形</h2>
<p>d_kamiさんに改良していただきました。ありがとうございます(^-^)</p>
<blockquote><p>String showTime(Calendar cal) {<br />
  Date date = cal.getTime();<br />
  SimpleDateFormat format = new SimpleDateFormat(&#8220;yyyy/MM/dd HH:mm&#8221;);<br />
  return format.format(date);<br />
}<br />
と書けばすっきりするよ、import java.text.SimpleDateFormatを忘れずに &#8211; <a href="http://d.hatena.ne.jp/d-kami/20090223/1235400686" title="SimpleDateFormat - マイペースなプログラミング日記" target="_blank">SimpleDateFormat &#8211; マイペースなプログラミング日記</a></p></blockquote>
<p>showTimeを修正して計りなおした実行結果は、</p>
<pre>
開始時刻: 2009/02/23 21:00
終了時刻: 2009/02/24 21:10
現時刻は指定期間「内」
</pre>
<p>確かに出力はyyyy/MM/dd HH:mmの形式になっていて見栄えも良いです。</p>
<h3>参考サイト</h3>
<ul>
<li><a href="http://java.sun.com/j2se/1.5.0/ja/docs/ja/api/java/util/GregorianCalendar.html" title="GregorianCalendar (Java 2 Platform SE 5.0)" target="_blank">GregorianCalendar (Java 2 Platform SE 5.0)</a></li>
<li><a href="http://java.sun.com/j2se/1.5.0/ja/docs/ja/api/java/text/SimpleDateFormat.html" title="SimpleDateFormat (Java 2 Platform SE 5.0)" target="_blank">SimpleDateFormat (Java 2 Platform SE 5.0)</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2008/06/python-date.html" rel="bookmark" title="2008年6月6日">Python: 現在の日付・時刻の取得と出力 &#8211; datetimeクラスの属性、today()、strftime()メソッド</a></li>
<li><a href="http://www.yukun.info/blog/2010/03/java-servlet-jsp-request-forward.html" rel="bookmark" title="2010年3月26日">Java: ServletからJSPへリクエストをフォワード</a></li>
<li><a href="http://www.yukun.info/blog/2008/11/php-form-submit-action-post.html" rel="bookmark" title="2008年11月8日">PHP: フォーム情報の送信・受信 &#8211; POSTメソッド</a></li>
<li><a href="http://www.yukun.info/blog/2008/03/arraylist-capacity.html" rel="bookmark" title="2008年3月6日">ArrayListのコンストラクタに初期容量を指定することで要素の追加処理を高速化</a></li>
<li><a href="http://www.yukun.info/blog/2008/05/out-of-memory-error.html" rel="bookmark" title="2008年5月8日">java.lang.OutOfMemoryErrorが発生する原因とその解決法の一例</a></li>
</ul>
<p><!-- Similar Posts took 13.707 ms --></p>
<p><a href="http://www.yukun.info/blog/2009/02/java-jsp-gregoriancalendar-period.html">Java, JSP: 現在時刻が指定期間内か判定する &#8211; GregorianCalendar#before、after</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2009/02/java-jsp-gregoriancalendar-period.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java, Swing: JComponentのGraphicsオブジェクトを用いて直線を描画</title>
		<link>http://www.yukun.info/blog/2009/02/java-swing-jcomponent-drawing-line.html</link>
		<comments>http://www.yukun.info/blog/2009/02/java-swing-jcomponent-drawing-line.html#comments</comments>
		<pubDate>Sat, 21 Feb 2009 12:30:54 +0000</pubDate>
		<dc:creator>yukun</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Swing]]></category>

		<guid isPermaLink="false">http://www.yukun.info/?p=1364</guid>
		<description><![CDATA[JComponentはほとんど全てのSwing コンポーネントの基底クラスで、Graphicsオブジェクトも持っています。下記のソースは、そのGraphicsを用いて画面に直線を描画するものです。 ソースコード pack &#8230; <a href="http://www.yukun.info/blog/2009/02/java-swing-jcomponent-drawing-line.html">Continue reading <span class="meta-nav">&#8594;</span></a><p><a href="http://www.yukun.info/blog/2009/02/java-swing-jcomponent-drawing-line.html">Java, Swing: JComponentのGraphicsオブジェクトを用いて直線を描画</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></description>
			<content:encoded><![CDATA[<p>JComponentはほとんど全てのSwing コンポーネントの基底クラスで、Graphicsオブジェクトも持っています。下記のソースは、そのGraphicsを用いて画面に直線を描画するものです。</p>
<h2>ソースコード</h2>
<pre>
package linecomp;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class LineComp extends JComponent {

  public static void main(String[] args) {
    Runnable myGUI = new Runnable() {
      @Override
      public void run() {
        JFrame win = new JFrame("Line Component");
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Insets ins = win.getInsets();
        win.setSize(300 + ins.left + ins.right, 300 + ins.top + ins.bottom);
        win.add(new LineComp());
        win.setVisible(true);
      }
    };
    SwingUtilities.invokeLater(myGUI); // 保留中のすべての AWT イベントが処理されたあとに発生
  }

  @Override
  public void paintComponent(Graphics g) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(Color.RED);
    g.drawLine(0, 0, getWidth(), getHeight());
  }
}
</pre>
<p>GUI部品の(再)描画レンダリングが発生した際、オーバーライドしたpaintComponent()内の手続きをEventQueueに登録しEDT(Event Dispatch Thread)が処理をします。標準のGUI部品をカスタマイズしたい場合などに使えます。その場合は予めsuper.paintComponent(g);でデフォルトのレンダリングを基底クラスに任せ、その後にカスタムの描画処理を書きます。</p>
<h2>実行結果</h2>
<p><a href="http://www.yukun.info/wp-content/uploads/line_component.jpg"><img src="http://www.yukun.info/wp-content/uploads/line_component.jpg" alt="JComponent に線を描画" title="line_component" width="300" height="300" class="size-full wp-image-1543" /></a></p>
<h3>追記: d_kami さんに改良して頂きました</h3>
<blockquote><p>InsetとJFrame#setSizeを使わずにJComponent#setPreferredSizeとJFrame#packを使うようにした &#8211; <a href="http://d.hatena.ne.jp/d-kami/20090222/1235274347" title="他のやり方 - マイペースなプログラミング日記" target="_blank">他のやり方 &#8211; マイペースなプログラミング日記</a></p></blockquote>
<pre>
comp.setPreferredSize(new Dimension(300, 300));
win.add(comp);
win.pack();
</pre>
<p>確かにsetPreferredSizeでコンポーネントのサイズを直接指定したほうが今プログラムの文脈に沿っています。私のほうはコンポーネントでなくJFrameのサイズの指定ですから。また、オーバーライドしたpaintComponent()でgetWidth()やgetHeight()を二度使うのであれば、一度ローカル変数に格納することでオーバヘッドを下げるのも大切ですね。日頃からの習慣にしないと。<br />
とても勉強になりました。ありがとうございます。</p>
<h3>参考サイト</h3>
<ul>
<li><a href="http://java.sun.com/javase/ja/6/docs/ja/api/javax/swing/JComponent.html" title="JComponent (Java Platform SE 6)" target="_blank">JComponent (Java Platform SE 6)</a></li>
<li><a href="http://java.sun.com/javase/ja/6/docs/ja/api/javax/swing/SwingUtilities.html" title="SwingUtilities (Java Platform SE 6)" target="_blank">SwingUtilities (Java Platform SE 6)</a></li>
</ul>
<h4>関連すると思われる記事：</h4>
<ul class="similar-posts">
<li><a href="http://www.yukun.info/blog/2010/01/android-draw-image-resources.html" rel="bookmark" title="2010年1月2日">Android: リソースの画像ファイルの拡大・縮小描画 &#8211; drawBitmap()</a></li>
<li><a href="http://www.yukun.info/blog/2011/02/java-tcp-socket-echo.html" rel="bookmark" title="2011年2月12日">Java: TCP Socket Echo Server/Client サンプル</a></li>
<li><a href="http://www.yukun.info/blog/2010/05/java-networkinterface-ipv6-ipv4.html" rel="bookmark" title="2010年5月16日">Java: インターフェースとローカルのIPv6, IPv4アドレスの取得 &#8211; NetworkInterfaceクラス</a></li>
<li><a href="http://www.yukun.info/blog/2008/11/actionscript-flash-load-server-image-file.html" rel="bookmark" title="2008年11月21日">ActionScript: 画像ファイルをダウンロードして表示 &#8211; Loaderクラス</a></li>
<li><a href="http://www.yukun.info/blog/2009/03/java-observe-event-model-view.html" rel="bookmark" title="2009年3月17日">Java: イベント駆動によるModelとViewの分離 &#8211; Observer パターン</a></li>
</ul>
<p><!-- Similar Posts took 18.485 ms --></p>
<p><a href="http://www.yukun.info/blog/2009/02/java-swing-jcomponent-drawing-line.html">Java, Swing: JComponentのGraphicsオブジェクトを用いて直線を描画</a> is a post from: <a href="http://www.yukun.info">Yukun&#039;s Blog</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.yukun.info/blog/2009/02/java-swing-jcomponent-drawing-line.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

